<?php
namespace app\index\controller;

use app\index\model\BidModel;
use app\index\model\CertModel;
use app\index\model\CertPersonModel;
use app\index\model\CertUseListModel;
use app\index\model\CertUseModel;
use app\index\model\ContractBuModel;
use app\index\model\ContractCaiJieModel;
use app\index\model\ContractCaiModel;
use app\index\model\ContractChuJieModel;
use app\index\model\ContractChuModel;
use app\index\model\ContractNeiModel;
use app\index\model\ContractShiJieModel;
use app\index\model\ContractShiModel;
use app\index\model\DealcomModel;
use app\index\model\DeptModel;
use app\index\model\EnginBeianModel;
use app\index\model\EnginBondShouModel;
use app\index\model\EnginBudgetModel;
use app\index\model\EnginChaModel;
use app\index\model\EnginChanModel;
use app\index\model\EnginDutyModel;
use app\index\model\EnginJunjieListModel;
use app\index\model\EnginJunjieModel;
use app\index\model\EnginJunyanModel;
use app\index\model\EnginKuaModel;
use app\index\model\EnginModel;
use app\index\model\EnginShuiModel;
use app\index\model\EnginTingModel;
use app\index\model\EnginXianModel;
use app\index\model\FileModel;
use app\index\model\FlowBillModel;
use app\index\model\FlowLogModel;
use app\index\model\HouChujinListModel;
use app\index\model\HouChushuiListModel;
use app\index\model\HouGonghuiModel;
use app\index\model\HouGongshuiListModel;
use app\index\model\HouGongshuiModel;
use app\index\model\HouGongzhiListModel;
use app\index\model\HouGongzhiModel;
use app\index\model\HouGongzhiQuModel;
use app\index\model\HouJieModel;
use app\index\model\HouKouFuwuModel;
use app\index\model\HouKouGongjieModel;
use app\index\model\HouKouKuaifeiModel;
use app\index\model\HouKouQifeiModel;
use app\index\model\HouKouShuifeiModel;
use app\index\model\HouShouModel;
use app\index\model\HouTiaoModel;
use app\index\model\IncomeEnginModel;
use app\index\model\KuaiJiModel;
use app\index\model\KuaiShouModel;
use app\index\model\PaymentBaoModel;
use app\index\model\PaymentEnginModel;
use app\index\model\PaymentNeifuModel;
use app\index\model\PaymentNeikouModel;
use app\index\model\PiaoChuListModel;
use app\index\model\PiaoKaiListModel;
use app\index\model\PiaokaiModel;
use app\index\model\PiaoShouListModel;
use app\index\model\PiaoShouModel;
use app\index\model\SuoHuiModel;
use app\index\model\UserModel;
use app\index\model\VisaModel;
use app\index\relevan\CertRelevan;
use app\index\relevan\EnginRelevan;
use app\index\service\BudgetService;
use app\index\service\CertService;
use app\index\service\ContractService;
use app\index\service\EnginService;
use app\index\service\FlowService;
use app\index\service\HouService;
use app\index\service\MenuService;
use app\index\service\OptService;
use app\index\service\UserService;
use think\Db;
use think\Exception;
use think\facade\Config;
use think\File;
use think\Request;

class Engin extends Common
{

    public function list_engin(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];
        $where[] = ['e.isturn','=',1];
        $where[] = ['e.status','in',[0,1]];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name|e.number|e.jiaer|e.gofuer|e.areas|e.gongzi|e.gongnei|e.guimo','like', '%'.$param['keyword'].'%'];
        }

        if(isset($param['lantake']) && !empty($param['lantake'])){
            $where[] = ['e.lantake','=', $param['lantake']];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['e.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['e.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['jiaer']) && !empty($param['jiaer'])){
            $where[] = ['e.jiaer','like', '%'.$param['jiaer'].'%'];
        }
        if(isset($param['gofuer']) && !empty($param['gofuer'])){
            $where[] = ['e.gofuer','like', '%'.$param['gofuer'].'%'];
        }
        if(isset($param['areas']) && !empty($param['areas'])){
            $where[] = ['e.areas','like', '%'.$param['areas'].'%'];
        }
        if(isset($param['gongzi']) && !empty($param['gongzi'])){
            $where[] = ['e.gongzi','like', '%'.$param['gongzi'].'%'];
        }
        if(isset($param['gongnei']) && !empty($param['gongnei'])){
            $where[] = ['e.gongnei','like', '%'.$param['gongnei'].'%'];
        }
        if(isset($param['guimo']) && !empty($param['guimo'])){
            $where[] = ['e.guimo','like', '%'.$param['guimo'].'%'];
        }
        if(isset($param['lanshi']) && !empty($param['lanshi'])){
            $where[] = ['e.lanshi','=', $param['lanshi']];
        }
        if(isset($param['gui_unit']) && !empty($param['gui_unit'])){
            $where[] = ['e.gui_unit','=', $param['gui_unit']];
        }
        if(isset($param['zhaotype']) && !empty($param['zhaotype'])){
            $where[] = ['e.zhaotype','=', $param['zhaotype']];
        }
        if(isset($param['kailei']) && !empty($param['kailei'])){
            $where[] = ['e.kailei','=', $param['kailei']];
        }
        if(isset($param['gonghelei']) && !empty($param['gonghelei'])){
            $where[] = ['e.gonghelei','=', $param['gonghelei']];
        }
        if(isset($param['win_unit']) && !empty($param['win_unit'])){
            $where[] = ['win_unit.name','like', '%'.$param['win_unit'].'%'];
        }
        if(isset($param['windt']) && !empty($param['windt'])){
            $where[] = ['e.windt','between', explode(' - ', $param['windt'])];
        }
        if(isset($param['state']) && !empty($param['state'])){
            $where[] = ['e.state','=', $param['state']];
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['e.status','=', $param['status']];
        }
        if(isset($param['chanid']) && !empty($param['chanid'])){
            $where[] = ['e.chanid','=', $param['chanid']];
        }


        $data['lantake'] = (new EnginService())->get_engin_lantake();
        $data['is_lantake'] = isset($param['lantake']) ? $param['lantake'] : '';

        $data['chanid'] = (new UserService())->get_chaninfo_all();
        $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';

        $data['win_unit'] = $data['chanid'];
        $data['is_win_unit'] = isset($param['win_unit']) ? $param['win_unit'] : '';
        $data['gui_unit'] = $data['chanid'];
        $data['is_gui_unit'] = isset($param['gui_unit']) ? $param['gui_unit'] : '';

        $data['lanshi'] = (new OptService())->get_base_info('bid_lanshi');
        $data['is_lanshi'] = isset($param['lanshi']) ? $param['lanshi'] : '';

        $data['gonghelei'] = (new OptService())->get_base_info('engin_gonghelei');
        $data['is_gonghelei'] = isset($param['gonghelei']) ? $param['gonghelei'] : '';

        $data['kailei'] = (new OptService())->get_base_info('bid_kailei');
        $data['is_kailei'] = isset($param['kailei']) ? $param['kailei'] : '';


        $data['zhaotype'] = (new OptService())->get_base_info('bid_zhaotype');
        $data['is_zhaotype'] = isset($param['zhaotype']) ? $param['zhaotype'] : '';

        $data['state'] = (new EnginService())->get_engin_state();
        $data['is_state'] = isset($param['state']) ? $param['state'] : '';


        if(isset($param['year']) && $param['year'] > 0){
            if(isset($param['month']) && $param['month'] > 0){
                $first_day = $param['year'].'-'.$param['month'].'-01';
                $last_day = date('Y-m-t', strtotime($first_day));
            }else{
                $first_day = $param['year'].'-01-01';
                $last_day = $param['year'].'-12-31';
            }
            $where[] = ['e.windt','between', [$first_day,$last_day]];
        }


        $data['data'] = EnginModel::alias('e')
            ->field('e.*,win_unit.name as win_unit_name,gui_unit.name as gui_unit_name')
            ->leftJoin('dept win_unit','win_unit.id=e.win_unit')
            ->leftJoin('dept gui_unit','gui_unit.id=e.gui_unit')
            ->where($where)
            ->where((new MenuService())->get_miss_where('engin', 'e'))
            ->order('e.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['chanid_name'] = DeptModel::get_name_by_pk($item['chanid']);

                $item['lanshi_name'] = (new OptService())->get_base_showname('bid_lanshi', $item['lanshi']);
                $item['kailei_name'] = (new OptService())->get_base_showname('bid_kailei', $item['kailei']);
                $item['gonghelei_name'] = (new OptService())->get_base_showname('engin_gonghelei', $item['gonghelei']);
                $item['zhaotype_name'] = (new OptService())->get_base_showname('bid_zhaotype', $item['zhaotype']);

                $item['gofutel'] = DealcomModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                    ->where(['name'=>$item['gofuer']])->value('liantel');

                $item['lantake_name'] = (new EnginService())->get_engin_lantake_name($item['lantake']);
                $item['state_name'] = (new EnginService())->get_engin_state_name($item);
                $item['state_name_wen'] = (new EnginService())->get_engin_state_name_tag($item);
                $item['created_user_name'] = UserModel::get_realname_by_pk($item['created_user']);
                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('engin');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_daijun(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];
        $where[] = ['e.isturn','=',1];
        $where[] = ['e.status','=',1];
        $where[] = ['e.state','in',[1,3]];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name|e.number|e.jiaer|e.gofuer|e.areas|e.gongzi|e.gongnei|e.guimo','like', '%'.$param['keyword'].'%'];
        }

        if(isset($param['lantake']) && !empty($param['lantake'])){
            $where[] = ['e.lantake','=', $param['lantake']];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['e.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['e.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['jiaer']) && !empty($param['jiaer'])){
            $where[] = ['e.jiaer','like', '%'.$param['jiaer'].'%'];
        }
        if(isset($param['gofuer']) && !empty($param['gofuer'])){
            $where[] = ['e.gofuer','like', '%'.$param['gofuer'].'%'];
        }
        if(isset($param['areas']) && !empty($param['areas'])){
            $where[] = ['e.areas','like', '%'.$param['areas'].'%'];
        }
        if(isset($param['gongzi']) && !empty($param['gongzi'])){
            $where[] = ['e.gongzi','like', '%'.$param['gongzi'].'%'];
        }
        if(isset($param['gongnei']) && !empty($param['gongnei'])){
            $where[] = ['e.gongnei','like', '%'.$param['gongnei'].'%'];
        }
        if(isset($param['guimo']) && !empty($param['guimo'])){
            $where[] = ['e.guimo','like', '%'.$param['guimo'].'%'];
        }
        if(isset($param['lanshi']) && !empty($param['lanshi'])){
            $where[] = ['e.lanshi','=', $param['lanshi']];
        }
        if(isset($param['gui_unit']) && !empty($param['gui_unit'])){
            $where[] = ['e.gui_unit','=', $param['gui_unit']];
        }
        if(isset($param['zhaotype']) && !empty($param['zhaotype'])){
            $where[] = ['e.zhaotype','=', $param['zhaotype']];
        }
        if(isset($param['kailei']) && !empty($param['kailei'])){
            $where[] = ['e.kailei','=', $param['kailei']];
        }
        if(isset($param['win_unit']) && !empty($param['win_unit'])){
            $where[] = ['win_unit.name','like', '%'.$param['win_unit'].'%'];
        }
        if(isset($param['windt']) && !empty($param['windt'])){
            $where[] = ['e.windt','between', explode(' - ', $param['windt'])];
        }
        if(isset($param['state']) && !empty($param['state'])){
            $where[] = ['e.state','=', $param['state']];
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['e.status','=', $param['status']];
        }
        if(isset($param['chanid']) && !empty($param['chanid'])){
            $where[] = ['e.chanid','=', $param['chanid']];
        }


        $data['lantake'] = (new EnginService())->get_engin_lantake();
        $data['is_lantake'] = isset($param['lantake']) ? $param['lantake'] : '';

        $data['chanid'] = (new UserService())->get_chaninfo_all();
        $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';

        $data['win_unit'] = $data['chanid'];
        $data['is_win_unit'] = isset($param['win_unit']) ? $param['win_unit'] : '';
        $data['gui_unit'] = $data['chanid'];
        $data['is_gui_unit'] = isset($param['gui_unit']) ? $param['gui_unit'] : '';

        $data['lanshi'] = (new OptService())->get_base_info('bid_lanshi');
        $data['is_lanshi'] = isset($param['lanshi']) ? $param['lanshi'] : '';

        $data['kailei'] = (new OptService())->get_base_info('bid_kailei');
        $data['is_kailei'] = isset($param['kailei']) ? $param['kailei'] : '';

        $data['zhaotype'] = (new OptService())->get_base_info('bid_zhaotype');
        $data['is_zhaotype'] = isset($param['zhaotype']) ? $param['zhaotype'] : '';

        $data['state'] = (new EnginService())->get_engin_state();
        $data['is_state'] = isset($param['state']) ? $param['state'] : '';


        if(isset($param['year']) && $param['year'] > 0){
            if(isset($param['month']) && $param['month'] > 0){
                $first_day = $param['year'].'-'.$param['month'].'-01';
                $last_day = date('Y-m-t', strtotime($first_day));
            }else{
                $first_day = $param['year'].'-01-01';
                $last_day = $param['year'].'-12-31';
            }
            $where[] = ['e.windt','between', [$first_day,$last_day]];
        }


        $info = EnginModel::alias('e')
            ->field('e.*,win_unit.name as win_unit_name,gui_unit.name as gui_unit_name')
            ->leftJoin('dept win_unit','win_unit.id=e.win_unit')
            ->leftJoin('dept gui_unit','gui_unit.id=e.gui_unit')
            ->where($where)
            ->where((new MenuService())->get_miss_where('engin', 'e'))
            ->order('e.id DESC')
            ->select()->toArray();

        $list = [];
        foreach ($info as $item){
            $shiinfo = ContractShiModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$item['id'],'deleted_user'=>0])->where(['isturn'=>1,'status'=>1])->find();
            if($shiinfo && $shiinfo['enddt'] && $shiinfo['enddt'] != '0000-00-00' && $shiinfo['enddt'] < date('Y-m-d')){
                $item['startdt'] = $shiinfo['startdt'];
                $item['enddt'] = $shiinfo['enddt'];


                $item['chanid_name'] = DeptModel::get_name_by_pk($item['chanid']);
                $item['lanshi_name'] = (new OptService())->get_base_showname('bid_lanshi', $item['lanshi']);
                $item['kailei_name'] = (new OptService())->get_base_showname('bid_kailei', $item['kailei']);
                $item['zhaotype_name'] = (new OptService())->get_base_showname('bid_zhaotype', $item['zhaotype']);
                $item['gofutel'] = DealcomModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                    ->where(['name'=>$item['gofuer']])->value('liantel');

                $item['lantake_name'] = (new EnginService())->get_engin_lantake_name($item['lantake']);
                $item['state_name'] = (new EnginService())->get_engin_state_name($item);
                $item['state_name_wen'] = (new EnginService())->get_engin_state_name_tag($item);
                $item['created_user_name'] = UserModel::get_realname_by_pk($item['created_user']);
                $list[] = $item;
            }
        }

        $data['data'] = $list;

        $data['butauth'] = [];
        $butauth = (new MenuService())->get_butauth('engin');
        foreach ($butauth as $mmm){
            if($mmm['butname'] == 'edit'){
                $data['butauth'][] = $mmm;
            }
        }
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_daijun222(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];
        $where[] = ['e.isturn','=',1];
        $where[] = ['e.status','=',1];
        $where[] = ['e.state','in',[1,3]];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name|e.number|e.jiaer|e.gofuer|e.areas|e.gongzi|e.gongnei|e.guimo','like', '%'.$param['keyword'].'%'];
        }

        if(isset($param['lantake']) && !empty($param['lantake'])){
            $where[] = ['e.lantake','=', $param['lantake']];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['e.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['e.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['jiaer']) && !empty($param['jiaer'])){
            $where[] = ['e.jiaer','like', '%'.$param['jiaer'].'%'];
        }
        if(isset($param['gofuer']) && !empty($param['gofuer'])){
            $where[] = ['e.gofuer','like', '%'.$param['gofuer'].'%'];
        }
        if(isset($param['areas']) && !empty($param['areas'])){
            $where[] = ['e.areas','like', '%'.$param['areas'].'%'];
        }
        if(isset($param['gongzi']) && !empty($param['gongzi'])){
            $where[] = ['e.gongzi','like', '%'.$param['gongzi'].'%'];
        }
        if(isset($param['gongnei']) && !empty($param['gongnei'])){
            $where[] = ['e.gongnei','like', '%'.$param['gongnei'].'%'];
        }
        if(isset($param['guimo']) && !empty($param['guimo'])){
            $where[] = ['e.guimo','like', '%'.$param['guimo'].'%'];
        }
        if(isset($param['lanshi']) && !empty($param['lanshi'])){
            $where[] = ['e.lanshi','=', $param['lanshi']];
        }
        if(isset($param['gui_unit']) && !empty($param['gui_unit'])){
            $where[] = ['e.gui_unit','=', $param['gui_unit']];
        }
        if(isset($param['zhaotype']) && !empty($param['zhaotype'])){
            $where[] = ['e.zhaotype','=', $param['zhaotype']];
        }
        if(isset($param['kailei']) && !empty($param['kailei'])){
            $where[] = ['e.kailei','=', $param['kailei']];
        }
        if(isset($param['win_unit']) && !empty($param['win_unit'])){
            $where[] = ['win_unit.name','like', '%'.$param['win_unit'].'%'];
        }
        if(isset($param['windt']) && !empty($param['windt'])){
            $where[] = ['e.windt','between', explode(' - ', $param['windt'])];
        }
        if(isset($param['state']) && !empty($param['state'])){
            $where[] = ['e.state','=', $param['state']];
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['e.status','=', $param['status']];
        }
        if(isset($param['chanid']) && !empty($param['chanid'])){
            $where[] = ['e.chanid','=', $param['chanid']];
        }


        $data['lantake'] = (new EnginService())->get_engin_lantake();
        $data['is_lantake'] = isset($param['lantake']) ? $param['lantake'] : '';

        $data['chanid'] = (new UserService())->get_chaninfo_all();
        $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';

        $data['win_unit'] = $data['chanid'];
        $data['is_win_unit'] = isset($param['win_unit']) ? $param['win_unit'] : '';
        $data['gui_unit'] = $data['chanid'];
        $data['is_gui_unit'] = isset($param['gui_unit']) ? $param['gui_unit'] : '';

        $data['lanshi'] = (new OptService())->get_base_info('bid_lanshi');
        $data['is_lanshi'] = isset($param['lanshi']) ? $param['lanshi'] : '';

        $data['kailei'] = (new OptService())->get_base_info('bid_kailei');
        $data['is_kailei'] = isset($param['kailei']) ? $param['kailei'] : '';

        $data['zhaotype'] = (new OptService())->get_base_info('bid_zhaotype');
        $data['is_zhaotype'] = isset($param['zhaotype']) ? $param['zhaotype'] : '';

        $data['state'] = (new EnginService())->get_engin_state();
        $data['is_state'] = isset($param['state']) ? $param['state'] : '';


        if(isset($param['year']) && $param['year'] > 0){
            if(isset($param['month']) && $param['month'] > 0){
                $first_day = $param['year'].'-'.$param['month'].'-01';
                $last_day = date('Y-m-t', strtotime($first_day));
            }else{
                $first_day = $param['year'].'-01-01';
                $last_day = $param['year'].'-12-31';
            }
            $where[] = ['e.windt','between', [$first_day,$last_day]];
        }

        $data['data'] = EnginModel::alias('e')
            ->field('e.*,win_unit.name as win_unit_name,gui_unit.name as gui_unit_name,shi.enddt,shi.startdt')
            ->leftJoin('dept win_unit','win_unit.id=e.win_unit')
            ->leftJoin('dept gui_unit','gui_unit.id=e.gui_unit')
            ->leftJoin('contract_shi shi','e.id=shi.enginid and shi.deleted_user=0 and shi.isturn=1 and shi.status=1')
            ->where($where)
            ->where("shi.enddt is not null and shi.enddt != '' and shi.enddt != '0000-00-00' and shi.enddt < '".date('Y-m-d')."'")
            ->where((new MenuService())->get_miss_where('engin', 'e'))
            ->order('e.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['chanid_name'] = DeptModel::get_name_by_pk($item['chanid']);

                $item['lanshi_name'] = (new OptService())->get_base_showname('bid_lanshi', $item['lanshi']);
                $item['kailei_name'] = (new OptService())->get_base_showname('bid_kailei', $item['kailei']);
                $item['zhaotype_name'] = (new OptService())->get_base_showname('bid_zhaotype', $item['zhaotype']);

                $item['gofutel'] = DealcomModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                    ->where(['name'=>$item['gofuer']])->value('liantel');

                $item['lantake_name'] = (new EnginService())->get_engin_lantake_name($item['lantake']);
                $item['state_name'] = (new EnginService())->get_engin_state_name($item);
                $item['state_name_wen'] = (new EnginService())->get_engin_state_name_tag($item);
                $item['created_user_name'] = UserModel::get_realname_by_pk($item['created_user']);
                return $item;
            })->toArray();

        $data['butauth'] = [];
        $butauth = (new MenuService())->get_butauth('engin');
        foreach ($butauth as $mmm){
            if($mmm['butname'] == 'edit'){
                $data['butauth'][] = $mmm;
            }
        }
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function del_engin(Request $request){
        $param = $request->post();
        $data = EnginModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        Db::startTrans();
        try {
            FlowBillModel::where(['id'=>$data['billid']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            EnginModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'engin', $data['id'], '工程承揽');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function yinbidfile_engin(Request $request){
        $bidid = $request->post('bidid', 0, 'int');

        //项目附件类型  招标文件【49】  投标文件【50】  中标通知书【129】
        $enginFiles = (new OptService())->get_file('engin');
        $bidFiles = (new OptService())->get_file('bid', $bidid);

        try{
            foreach ($bidFiles as $item){
                if($item['name'] == '招标文件'){
                    $children = $item['children'];
                    foreach ($children as $vvv){
                        unset($vvv['id']);
                        unset($vvv['created_user_name']);
                        $vvv['typeid'] = 49;
                        $vvv['table'] = '';
                        $vvv['mid'] = 0;
                        $vvv['created_at'] = date("Y-m-d H:i:s");
                        $vvv['created_user'] = $this->userinfo['id'];
                        $fffid = FileModel::insertGetId($vvv);

                        $encpath =  encrypt($fffid, 'E', Config::get('service.info_key'));
                        if(FileModel::where(['id'=>$fffid])->update(['encpath'=>$encpath]) === false){
                            throw new Exception("操作失败");
                        }

                        $fffarr = FileModel::where(['id'=>$fffid])->find();
                        foreach ($enginFiles as &$envv){
                            if($envv['id'] == $fffarr['typeid']){
                                $envv['children'][] = $fffarr;
                            }
                        }
                    }
                }

                if($item['name'] == '投标文件'){
                    $children = $item['children'];
                    foreach ($children as $vvv){
                        unset($vvv['id']);
                        unset($vvv['created_user_name']);
                        $vvv['typeid'] = 50;
                        $vvv['table'] = '';
                        $vvv['mid'] = 0;
                        $vvv['created_at'] = date("Y-m-d H:i:s");
                        $vvv['created_user'] = $this->userinfo['id'];
                        $fffid = FileModel::insertGetId($vvv);

                        $encpath =  encrypt($fffid, 'E', Config::get('service.info_key'));
                        if(FileModel::where(['id'=>$fffid])->update(['encpath'=>$encpath]) === false){
                            throw new Exception("操作失败");
                        }

                        $fffarr = FileModel::where(['id'=>$fffid])->find();
                        foreach ($enginFiles as &$envv){
                            if($envv['id'] == $fffarr['typeid']){
                                $envv['children'][] = $fffarr;
                            }
                        }
                    }
                }

                if($item['name'] == '中标通知书'){
                    $children = $item['children'];
                    foreach ($children as $vvv){
                        unset($vvv['id']);
                        unset($vvv['created_user_name']);
                        $vvv['typeid'] = 129;
                        $vvv['table'] = '';
                        $vvv['mid'] = 0;
                        $vvv['created_at'] = date("Y-m-d H:i:s");
                        $vvv['created_user'] = $this->userinfo['id'];
                        $fffid = FileModel::insertGetId($vvv);

                        $encpath =  encrypt($fffid, 'E', Config::get('service.info_key'));
                        if(FileModel::where(['id'=>$fffid])->update(['encpath'=>$encpath]) === false){
                            throw new Exception("操作失败");
                        }

                        $fffarr = FileModel::where(['id'=>$fffid])->find();
                        foreach ($enginFiles as &$envv){
                            if($envv['id'] == $fffarr['typeid']){
                                $envv['children'][] = $fffarr;
                            }
                        }
                    }
                }
            }
        }catch (\Exception $e){
            $return_data['msg'] = $e->getMessage();
            return outputJson(4000, "附件引入失败，请重新引入");
        }


        $data['files'] = $enginFiles;
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function show_engin(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = EnginModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }

        $data['data']['gofutel'] = DealcomModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['name'=>$data['data']['gofuer']])->value('liantel');
        $data['data']['lantake_name'] = (new EnginService())->get_engin_lantake_name($data['data']['lantake']);
        $data['data']['state_name'] = (new EnginService())->get_engin_state_name($data['data']);
        $data['data']['state_name_wen'] = (new EnginService())->get_engin_state_name_tag($data['data']);
        $data['data']['win_unit_name'] = DeptModel::where(['id'=>$data['data']['win_unit']])->value('name');
        $data['data']['gui_unit_name'] = DeptModel::where(['id'=>$data['data']['gui_unit']])->value('name');

        $data['data']['lanshi_name'] = (new OptService())->get_base_showname('bid_lanshi', $data['data']['lanshi']);
        $data['data']['kailei_name'] = (new OptService())->get_base_showname('bid_kailei', $data['data']['kailei']);
        $data['data']['gonghelei_name'] = (new OptService())->get_base_showname('engin_gonghelei', $data['data']['gonghelei']);
        $data['data']['zhaotype_name'] = (new OptService())->get_base_showname('bid_zhaotype', $data['data']['zhaotype']);


        $data['files'] = (new OptService())->get_file('engin', $data['data']['id']);
        $data['billinfo'] = (new FlowService())->get_flow_show_info($data['data']['billid']);
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function xiang_engin(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = EnginModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }

        $data['data']['gofutel'] = DealcomModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['name'=>$data['data']['gofuer']])->value('liantel');

        $data['data']['lantake_name'] = (new EnginService())->get_engin_lantake_name($data['data']['lantake']);
        $data['data']['state_name'] = (new EnginService())->get_engin_state_name($data['data']);
        $data['data']['state_name_wen'] = (new EnginService())->get_engin_state_name_tag($data['data']);
        $data['data']['win_unit_name'] = DeptModel::where(['id'=>$data['data']['win_unit']])->value('name');
        $data['data']['gui_unit_name'] = DeptModel::where(['id'=>$data['data']['gui_unit']])->value('name');

        $data['data']['lanshi_name'] = (new OptService())->get_base_showname('bid_lanshi', $data['data']['lanshi']);
        $data['data']['kailei_name'] = (new OptService())->get_base_showname('bid_kailei', $data['data']['kailei']);
        $data['data']['zhaotype_name'] = (new OptService())->get_base_showname('bid_zhaotype', $data['data']['zhaotype']);


        $data['neiinfo'] = ContractNeiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['enginid'=>$data['data']['id']])->find();
        if($data['neiinfo']){
            $data['neiinfo']['state_name'] = (new ContractService())->get_contract_nei_state_name($data['neiinfo']['state']);
        }

        $data['shiinfo'] = ContractShiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['enginid'=>$data['data']['id']])->find();
        if($data['shiinfo']){
            $data['shiinfo']['bumoney'] = ContractBuModel::where(['shiid'=>$data['shiinfo']['id'],'deleted_user'=>0])
                ->where(['status'=>1,'isturn'=>1])->sum('money');
            $data['shiinfo']['money'] += $data['shiinfo']['bumoney'];
        }

        $data['shijiemoney'] = ContractShiJieModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['enginid'=>$data['data']['id']])->sum('money');


        $data['piaokaifee'] = PiaoKaiListModel::alias('list')
            ->join('piao_kai kai','kai.id=list.kaiid')
            ->where(['kai.comid'=>$this->userinfo['comid'],'kai.deleted_user'=>0,'kai.isturn'=>1,'kai.status'=>1])
            ->where(['kai.enginid'=>$data['data']['id']])
            ->sum('list.money');
        $data['piaokairatefee'] = PiaoKaiListModel::alias('list')
            ->join('piao_kai kai','kai.id=list.kaiid')
            ->where(['kai.comid'=>$this->userinfo['comid'],'kai.deleted_user'=>0,'kai.isturn'=>1,'kai.status'=>1])
            ->where(['kai.enginid'=>$data['data']['id']])
            ->sum('list.ratefee');

        $data['gonghuimoney'] = (new HouService())->get_hou_gonghui_money($data['data']['id']);




        $data['huinokai'] = round($data['gonghuimoney'] - $data['piaokaifee'], 2);
        $data['huinokai'] = $data['huinokai'] > 0 ? $data['huinokai'] : 0;

        $data['kainohui'] = round($data['piaokaifee'] - $data['gonghuimoney'], 2);
        $data['kainohui'] = $data['kainohui'] > 0 ? $data['kainohui'] : 0;


        $data['yikaiweihuifee'] = round($data['piaokaifee'] - $data['gonghuimoney'], 2);

        //当前工程的工程销项票金额÷【结算 > 施工合同金额 > 中标价】×100%
        $data['leixiaobi'] = 0;
        if($data['shijiemoney'] > 0){
            $data['leixiaobi'] = round($data['piaokaifee'] / $data['shijiemoney'] * 100, 2);
        }else{
            if($data['shiinfo'] && $data['shiinfo']['money'] > 0){
                $data['leixiaobi'] = round($data['piaokaifee'] / $data['shiinfo']['money'] * 100, 2);
            }else{
                if($data['data']['winfee'] > 0){
                    $data['leixiaobi'] = round($data['piaokaifee'] / $data['data']['winfee'] * 100, 2);
                }
            }
        }

        //累计工程回款÷【结算 > 施工合同金额 > 中标价】X100%
        $data['leihuibi'] = 0;
        if($data['shijiemoney'] > 0){
            $data['leihuibi'] = round($data['gonghuimoney'] / $data['shijiemoney']*100, 2);
        }else{
            if($data['shiinfo'] && $data['shiinfo']['money'] > 0){
                $data['leihuibi'] = round($data['gonghuimoney'] / $data['shiinfo']['money']*100, 2);
            }else{
                if($data['data']['winfee'] > 0){
                    $data['leihuibi'] = round($data['gonghuimoney'] / $data['data']['winfee']*100, 2);
                }
            }
        }

        $data['gongzhimoney'] = (new HouService())->get_hou_gongzhi_money($data['data']['id']);
        $data['gongzhimoneygogong'] = (new HouService())->get_hou_gongzhi_money_gogong($data['data']['id']);

        $data['piaoshoumoney'] = PiaoShouModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['enginid'=>$data['data']['id']])->sum('money');
        $data['piaoshouratefee'] = PiaoShouModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['enginid'=>$data['data']['id']])->sum('ratefee');

        $data['contractcaimoney'] = ContractCaiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['enginid'=>$data['data']['id']])->sum('money');
        $data['contractcaijiemoney'] = ContractCaiJieModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['enginid'=>$data['data']['id']])->sum('money');

        $data['hougongshuimoney'] = HouGongshuiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['enginid'=>$data['data']['id']])->sum('money');

        //施工合同金额（结算优先）X劳务分包服务费率÷100
        $data['yingkoufuwu'] = 0;
        if($data['neiinfo'] && $data['neiinfo']['ratefu']){
            if($data['shijiemoney']){
                $data['yingkoufuwu'] = round($data['shijiemoney'] * $data['neiinfo']['ratefu'] / 100, 2);
            }else{
                if($data['shiinfo'] && $data['shiinfo']['money']){
                    $data['yingkoufuwu'] = round($data['shiinfo']['money'] * $data['neiinfo']['ratefu'] / 100, 2);
                }
            }
        }

        $data['yikoufuwu'] = HouKouFuwuModel::alias('list')
            ->join('hou_gonghui hou','hou.id=list.zhuid')
            ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
            ->where(['list.type'=>1, 'list.enginid'=>$data['data']['id']])
            ->sum('list.koufee');
        $data['yikoufuwu'] += HouKouFuwuModel::alias('list')
            ->join('hou_gongyu hou','hou.id=list.zhuid')
            ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
            ->where(['list.type'=>2, 'list.enginid'=>$data['data']['id']])
            ->sum('list.koufee');

        //工程销项票金额（元）X税款保证金费率 ÷100
        $data['yingkoushuifei'] = 0;
        if($data['neiinfo'] && $data['neiinfo']['rateshui'] && $data['piaokaifee']){
            $data['yingkoushuifei'] = round($data['piaokaifee'] * $data['neiinfo']['rateshui'] / 100, 2);
        }
        $data['yikoushuifei'] = HouKouShuifeiModel::alias('list')
            ->join('hou_gonghui hou','hou.id=list.zhuid')
            ->join('engin_shui shui','shui.id=list.shuiid')
            ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
            ->where(['shui.comid'=>$this->userinfo['comid'],'shui.deleted_user'=>0,'shui.isturn'=>1,'shui.status'=>1])
            ->where(['list.type'=>1, 'shui.enginid'=>$data['data']['id']])
            ->sum('list.koufee');

        $data['yikoushuifei'] += HouKouShuifeiModel::alias('list')
            ->join('hou_gongyu hou','hou.id=list.zhuid')
            ->join('engin_shui shui','shui.id=list.shuiid')
            ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
            ->where(['shui.comid'=>$this->userinfo['comid'],'shui.deleted_user'=>0,'shui.isturn'=>1,'shui.status'=>1])
            ->where(['list.type'=>2, 'shui.enginid'=>$data['data']['id']])
            ->sum('list.koufee');


        $data['yingkuaifei'] = KuaiJiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['enginid'=>$data['data']['id'],'isgua'=>'是'])->sum('kuaifee');
        $data['yingkuaifei'] += KuaiShouModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['enginid'=>$data['data']['id'],'isgua'=>'是'])->sum('kuaifee');

        $data['yikuaifei'] = HouKouKuaifeiModel::alias('list')
            ->join('hou_gongyu hou','hou.id=list.zhuid')
            ->join('kuai_ji kuai','kuai.id=list.kuaiid')
            ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
            ->where(['kuai.comid'=>$this->userinfo['comid'],'kuai.deleted_user'=>0,'kuai.isturn'=>1,'kuai.status'=>1])
            ->where(['list.type'=>2,'list.kuaitype'=>1, 'kuai.enginid'=>$data['data']['id']])
            ->sum('list.koufee');

        $data['yikuaifei'] += HouKouKuaifeiModel::alias('list')
            ->join('hou_gongyu hou','hou.id=list.zhuid')
            ->join('kuai_shou kuai','kuai.id=list.kuaiid')
            ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
            ->where(['kuai.comid'=>$this->userinfo['comid'],'kuai.deleted_user'=>0,'kuai.isturn'=>1,'kuai.status'=>1])
            ->where(['list.type'=>2,'list.kuaitype'=>2, 'kuai.enginid'=>$data['data']['id']])
            ->sum('list.koufee');


        $data['yiqifeizhi'] = HouKouQifeiModel::alias('list')
            ->join('hou_gonghui hou','hou.id=list.zhuid')
            ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
            ->where(['list.type'=>1, 'list.enginid'=>$data['data']['id']])
            ->where('houkoulei','eq',2)
            ->sum('list.koufee');

        $data['yiqifeizhi'] += HouKouQifeiModel::alias('list')
            ->join('hou_gongyu hou','hou.id=list.zhuid')
            ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
            ->where(['list.type'=>2, 'list.enginid'=>$data['data']['id']])
            ->where('houkoulei','eq',2)
            ->sum('list.koufee');

        $data['yiqifei'] = HouKouQifeiModel::alias('list')
            ->join('hou_gonghui hou','hou.id=list.zhuid')
            ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
            ->where(['list.type'=>1, 'list.enginid'=>$data['data']['id']])
            ->where('houkoulei','neq',2)
            ->sum('list.koufee');

        $data['yiqifei'] += HouKouQifeiModel::alias('list')
            ->join('hou_gongyu hou','hou.id=list.zhuid')
            ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
            ->where(['list.type'=>2, 'list.enginid'=>$data['data']['id']])
            ->where('houkoulei','neq',2)
            ->sum('list.koufee');


        $data['yishoushuili'] = round($data['yikoushuifei'] + $data['yiqifeizhi'], 2);
        $data['leikoushoufee'] = round($data['yikoufuwu'] + $data['yishoushuili'] + $data['yikuaifei'] + $data['yiqifei'], 2);



        $data['gongzhimoneyquben'] = (new HouService())->get_hou_gongzhi_money_quben($data['data']['id']);
        $data['gonghuikoufee'] = HouGonghuiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['enginid'=>$data['data']['id']])->sum('koufee');

        $data['qizankoufee'] = HouKouQifeiModel::alias('list')
            ->join('hou_gonghui hou','hou.id=list.zhuid')
            ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
            ->where(['list.type'=>1, 'list.enginid'=>$data['data']['id'],'kouxing'=>'暂扣'])
            ->sum('list.koufee');



        $data['jiedongkoufee'] = HouKouQifeiModel::alias('list')
            ->join('hou_gonghui hou','hou.id=list.zhuid')
            ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
            ->where(['list.type'=>1, 'list.enginid'=>$data['data']['id'],'isdong'=>1])
            ->sum('list.koufee');

        $data['jiedongkoufee'] += HouKouQifeiModel::alias('list')
            ->join('hou_gongyu hou','hou.id=list.zhuid')
            ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
            ->where(['list.type'=>2, 'list.enginid'=>$data['data']['id'],'isdong'=>1])
            ->sum('list.koufee');

        $data['yuliufee'] = round($data['qizankoufee'] - $data['jiedongkoufee'], 2);
        $data['gonghui_keyu'] = round($data['gonghuimoney'] - $data['gongzhimoneyquben'] - $data['gonghuikoufee'] + $data['jiedongkoufee'], 2);


        $data['gongshouzhicha'] = round($data['gonghuimoney'] - $data['gongzhimoney'], 2);

        $data['cha_dainum'] = EnginChaModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['isxu'=>'是', 'iszheng'=>'否', 'enginid'=>$data['data']['id']])
            ->count();


        $data['gongzhimoney_dang'] = HouGongzhiQuModel::alias('qu')
            ->join('hou_gongzhi_list list','list.id=qu.gongzhilistid')
            ->join('hou_gongzhi zhi','zhi.id=qu.gongzhiid')
            ->where(['zhi.comid'=>$this->userinfo['comid'],'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
            ->where(['qu.type'=>2, 'zhi.enginid'=>$data['data']['id']])
            ->sum('qu.money');

        $data['gongzhimoney_yufu'] = HouGongzhiQuModel::alias('qu')
            ->join('hou_gongzhi_list list','list.id=qu.gongzhilistid')
            ->join('hou_gongzhi zhi','zhi.id=qu.gongzhiid')
            ->where(['zhi.comid'=>$this->userinfo['comid'],'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
            ->where(['qu.type'=>1, 'zhi.enginid'=>$data['data']['id']])
            ->sum('qu.money');

        $data['gongzhimoney_qita'] = HouGongzhiQuModel::alias('qu')
            ->join('hou_gongzhi_list list','list.id=qu.gongzhilistid')
            ->join('hou_gongzhi zhi','zhi.id=qu.gongzhiid')
            ->where(['zhi.comid'=>$this->userinfo['comid'],'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
            ->where(['qu.type'=>3, 'zhi.enginid'=>$data['data']['id']])
            ->sum('qu.money');



        $data['gongzhimoneygogong_dang'] = HouGongzhiQuModel::alias('qu')
            ->join('hou_gongzhi_list list','list.id=qu.gongzhilistid')
            ->join('hou_gongzhi zhi','zhi.id=qu.gongzhiid')
            ->join('dealcom deal','deal.name=list.fuer')
            ->where(['zhi.comid'=>$this->userinfo['comid'],'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
            ->where(['deal.type'=>3,'qu.type'=>2, 'zhi.enginid'=>$data['data']['id']])
            ->sum('qu.money');

        $data['gongzhimoneygogong_yufu'] = HouGongzhiQuModel::alias('qu')
            ->join('hou_gongzhi_list list','list.id=qu.gongzhilistid')
            ->join('hou_gongzhi zhi','zhi.id=qu.gongzhiid')
            ->join('dealcom deal','deal.name=list.fuer')
            ->where(['zhi.comid'=>$this->userinfo['comid'],'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
            ->where(['deal.type'=>3,'qu.type'=>1, 'zhi.enginid'=>$data['data']['id']])
            ->sum('qu.money');
        $data['gongzhimoneygogong_qita'] = HouGongzhiQuModel::alias('qu')
            ->join('hou_gongzhi_list list','list.id=qu.gongzhilistid')
            ->join('hou_gongzhi zhi','zhi.id=qu.gongzhiid')
            ->join('dealcom deal','deal.name=list.fuer')
            ->where(['zhi.comid'=>$this->userinfo['comid'],'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
            ->where(['deal.type'=>3,'qu.type'=>3, 'zhi.enginid'=>$data['data']['id']])
            ->sum('qu.money');


        $data['nodishuifei'] = round($data['piaoshouratefee'] - $data['hougongshuimoney'], 2);


        $data['files'] = (new OptService())->get_file('engin', $data['data']['id']);
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function gofuer_engin(Request $request){
        $gofuer = $request->post('gofuer', '', 'string');
        $data['gofuer'] = $gofuer;
        $data['gofutel'] = DealcomModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['name'=>$data['gofuer']])->value('liantel');

        $data['hougonghuikeyong'] = 0;
        $enList = EnginModel::field('id')->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['gofuer'=>$data['gofuer']])->select();
        foreach ($enList as $item){
            $item['hougonghuimoney'] = (new HouService())->get_hou_gonghui_money($item['id']);
            $item['hougongzhimoneyquben'] = (new HouService())->get_hou_gongzhi_money_quben($item['id']);
            $item['hougonghuikoufee'] = (new HouService())->get_hou_gonghui_koufee($item['id']);
            $item['jiedongkoufee'] = HouKouQifeiModel::alias('list')
                ->join('hou_gonghui hou','hou.id=list.zhuid')
                ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                ->where(['list.type'=>1, 'list.enginid'=>$item['id'],'isdong'=>1])
                ->sum('list.koufee');
            $data['hougonghuikeyong'] += round($item['hougonghuimoney'] - $item['hougongzhimoneyquben'] - $item['hougonghuikoufee'] + $item['jiedongkoufee'], 2);
        }


        $hougongyumoney = (new HouService())->get_hou_gongyu_money($data['gofuer']);
        $hougongyukoufee = (new HouService())->get_hou_gongyu_koufee($data['gofuer']);
        $hougongzhimoneyqugoer = (new HouService())->get_hou_gongzhi_money_qugoer($data['gofuer']);
        $jiedongkoufee = HouKouQifeiModel::alias('list')
            ->join('hou_gongyu hou','hou.id=list.zhuid')
            ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
            ->where(['list.type'=>2, 'hou.gofuer'=>$data['gofuer'],'isdong'=>1])
            ->sum('list.koufee');
        $hougongshuimoneygoquan = (new HouService())->get_hou_gongshui_money_goquan($data['gofuer']);
        $data['hougongyukeyong'] = round($hougongyumoney-$hougongyukoufee-$hougongzhimoneyqugoer+$jiedongkoufee+$hougongshuimoneygoquan,2);


        $data['allkeyong'] = round($data['hougonghuikeyong'] + $data['hougongyukeyong'], 2);


        $data['daihuanjiefee'] = 0;
        $jieList = HouJieModel::field('id,money')->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['jieer'=>$data['gofuer']])->select();
        foreach ($jieList as $vvv){
            $yikouHui = HouKouGongjieModel::alias('list')
                ->field('hou.*,list.youfee')
                ->join('hou_gonghui hou','hou.id=list.zhuid')
                ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                ->where(['list.type'=>1,'list.jieid'=>$vvv['id']])
                ->find();
            if($yikouHui){
                continue;
            }

            $yikouYu = HouKouGongjieModel::alias('list')
                ->field('hou.*,list.youfee')
                ->join('hou_gongyu hou','hou.id=list.zhuid')
                ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                ->where(['list.type'=>2,'list.jieid'=>$vvv['id']])
                ->find();
            if($yikouYu){
                continue;
            }
            $data['daihuanjiefee'] += $vvv['money'];
        }



        $list_gonghui = EnginModel::field('*')->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['gofuer'=>$data['gofuer']])->select()->toArray();
        foreach ($list_gonghui as &$item){
            $item['shiinfo'] = ContractShiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])->where(['enginid'=>$item['id']])->find();
            $item['shimoney'] = (new EnginService())->get_contract_shi_money($item['id']);
            $item['shijiemoney'] = (new EnginService())->get_contract_shi_jie_money($item['id']);

            $item['hougonghuimoney'] = (new HouService())->get_hou_gonghui_money($item['id']);
            $item['hougongzhimoneyquben'] = (new HouService())->get_hou_gongzhi_money_quben($item['id']);
            $item['hougonghuikoufee'] = (new HouService())->get_hou_gonghui_koufee($item['id']);
            $item['qizankoufee'] = HouKouQifeiModel::alias('list')
                ->join('hou_gonghui hou','hou.id=list.zhuid')
                ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                ->where(['list.type'=>1, 'list.enginid'=>$item['id'],'kouxing'=>'暂扣'])
                ->sum('list.koufee');

            $item['jiedongkoufee'] = HouKouQifeiModel::alias('list')
                ->join('hou_gonghui hou','hou.id=list.zhuid')
                ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                ->where(['list.type'=>1, 'list.enginid'=>$item['id'],'isdong'=>1])
                ->sum('list.koufee');
            $item['yuliufee'] = round($item['qizankoufee'] - $item['jiedongkoufee'], 2);
            $item['hougonghuikeyong'] = round($item['hougonghuimoney'] - $item['hougongzhimoneyquben'] - $item['hougonghuikoufee'] + $item['jiedongkoufee'], 2);
        }
        $data['list_gonghui'] = $list_gonghui;



        $list_gongyu = [['gofuer'=>$data['gofuer']]];
        foreach ($list_gongyu as &$item){
            $item['hougongyumoney'] = (new HouService())->get_hou_gongyu_money($item['gofuer']);
            $item['hougongyukoufee'] = (new HouService())->get_hou_gongyu_koufee($item['gofuer']);
            $item['hougongzhimoneyqugoer'] = (new HouService())->get_hou_gongzhi_money_qugoer($item['gofuer']);

            $item['qizankoufee'] = HouKouQifeiModel::alias('list')
                ->join('hou_gongyu hou','hou.id=list.zhuid')
                ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                ->where(['list.type'=>2, 'hou.gofuer'=>$item['gofuer'],'kouxing'=>'暂扣'])
                ->sum('list.koufee');


            $item['jiedongkoufee'] = HouKouQifeiModel::alias('list')
                ->join('hou_gongyu hou','hou.id=list.zhuid')
                ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                ->where(['list.type'=>2, 'hou.gofuer'=>$item['gofuer'],'isdong'=>1])
                ->sum('list.koufee');


            $item['yuliufee'] = round($item['qizankoufee'] - $item['jiedongkoufee'], 2);

            $item['hougongshuimoneygoquan'] = (new HouService())->get_hou_gongshui_money_goquan($item['gofuer']);
            $item['hougongyukeyong'] = round($item['hougongyumoney']-$item['hougongyukoufee']-$item['hougongzhimoneyqugoer']+$item['jiedongkoufee']+$item['hougongshuimoneygoquan'],2);

        }
        $data['list_gongyu'] = $list_gongyu;



        $list_houjie = HouJieModel::field('*')->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['jieer'=>$data['gofuer']])->select()->toArray();
        foreach ($list_houjie as &$item){
            $item['fangtype_name'] = (new OptService())->get_base_showname('cai_jie_fangtype', $item['fangtype']);
            $item['state_name'] = (new ContractService())->get_contract_cai_state_name_tag($item['id'], $item['state']);

            $item['statename'] = '未还款';
            $daodt = date("Y-m-d H:i:s");
            $item['youfee'] = '';
            $item['koufee'] = '';
            $item['huandt'] = '';

            $yikouHui = HouKouGongjieModel::alias('list')
                ->field('hou.*,list.youfee')
                ->join('hou_gonghui hou','hou.id=list.zhuid')
                ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                ->where(['list.type'=>1,'list.jieid'=>$item['id']])
                ->find();
            if($yikouHui){
                $item['statename'] = '已还款';
                $daodt = $yikouHui['dt'];
                $item['youfee'] = $yikouHui['youfee'];
                $item['koufee'] = $yikouHui['koufee'];
                $item['huandt'] = $yikouHui['dt'];
            }
            $yikouYu = HouKouGongjieModel::alias('list')
                ->field('hou.*,list.youfee')
                ->join('hou_gongyu hou','hou.id=list.zhuid')
                ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                ->where(['list.type'=>2,'list.jieid'=>$item['id']])
                ->find();
            if($yikouYu){
                $item['statename'] = '已还款';
                $daodt = $yikouYu['dt'];
                $item['youfee'] = $yikouYu['youfee'];
                $item['koufee'] = $yikouYu['koufee'];
                $item['huandt'] = $yikouYu['dt'];
            }



            $item['yueshu'] = 0;
            $item['lixifee'] = 0;
            $item['fangkuandt'] = '';
            //月数  （还款日期 - 放款日期 + 1）/ 30
            //利息  月数   * 月利息 / 100 * 借款金额
            $houshou = HouShouModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                ->where(['jieid'=>$item['id']])->order('daodt ASC')->find();
            if($houshou){
                $item['fangkuandt'] = $houshou['daodt'];
                $item['yueshu'] = ceil(  (( strtotime($daodt) - strtotime($item['fangkuandt']))/86400 + 1)/30);
                $item['yueshu'] = $item['yueshu'] > 0 ? $item['yueshu'] : 0;
                $item['lixifee'] = round($item['yueshu'] * $item['yuerate'] / 100 * $item['money'], 2);
            }
            $item['yinghuanfee'] = round($item['money']+$item['lixifee'],2);
        }
        $data['list_houjie'] = $list_houjie;


        return outputJson(2000,lang('code_2000'), $data);
    }
    public function yu_engin(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if($param['is_yu'] == '是'){
                if($param['yu_cai'] == ''){
                    return outputJson(4000, '请输入材料费占比阈值');
                }
                if($param['yu_lao'] == ''){
                    return outputJson(4000, '请输入劳务人工费占比阈值');
                }
                if($param['yu_zu'] == ''){
                    return outputJson(4000, '请输入机械租赁费占比阈值');
                }
                if($param['yu_fen'] == ''){
                    return outputJson(4000, '请输入专业分包费占比阈值');
                }
                if($param['yu_qi'] == ''){
                    return outputJson(4000, '请输入其他费占比阈值');
                }
                if(empty($param['yuer'])){
                    return outputJson(4000, '请选择预警通知对象');
                }

                $yu_heji = $param['yu_cai'] + $param['yu_lao'] + $param['yu_zu'] + $param['yu_fen'] + $param['yu_qi']+100;
                if($yu_heji != 200){
                    return outputJson(4000, '当前合计比例必须设为100');
                }
            }else{
                $param['yu_cai'] = '';
                $param['yu_lao'] = '';
                $param['yu_zu'] = '';
                $param['yu_fen'] = '';
                $param['yu_qi'] = '';
                $param['yuer'] = '';
            }





            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            unset($param['token']);


            Db::startTrans();
            try {
                EnginModel::update($param);

                (new OptService())->add_flow_log('成本预警设置', 'engin', $param['id']);
                (new OptService())->add_log_list('成本预警设置', 'engin', $param['id'], '工程承揽');

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }
            $data['data']['yuer_info'] = (new UserService())->get_users_part_arr($data['data']['yuer'], 'user');
            return outputJson(2000,lang('code_2000'),$data);
        }
    }


    public function list_engin_jing_cha(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];
        $where[] = ['e.deleted_user','=',0];
        $where[] = ['e.isturn','=',1];
        $where[] = ['e.status','=',1];

        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['e.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['e.number','like', '%'.$param['number'].'%'];
        }

        $data['data'] = EnginModel::alias('e')
            ->field('e.*')
            ->where($where)
            ->order('e.created_at DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['yearcur'] = date('Y');
                $item['chanid_name'] = DeptModel::get_name_by_pk($item['chanid']);

                $item['lanshi_name'] = (new OptService())->get_base_showname('bid_lanshi', $item['lanshi']);
                $item['kailei_name'] = (new OptService())->get_base_showname('bid_kailei', $item['kailei']);
                $item['zhaotype_name'] = (new OptService())->get_base_showname('bid_zhaotype', $item['zhaotype']);

                $item['lantake_name'] = (new EnginService())->get_engin_lantake_name($item['lantake']);
                $item['state_name'] = (new EnginService())->get_engin_state_name($item);
                $item['state_name_wen'] = (new EnginService())->get_engin_state_name_tag($item);
                $item['created_user_name'] = UserModel::get_realname_by_pk($item['created_user']);

                $item['gofutel'] = DealcomModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                    ->where(['name'=>$item['gofuer']])->value('liantel');
                return $item;
            })->toArray();
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_jing_cha22(Request $request){
        $param = $request->post();
        $list = EnginModel::field('id,id as value,name,name as title')->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'status'=>1,'isturn'=>1])
            ->order('created_at DESC')->select()->toArray();

        $data['data'] = $list;
        return outputJson(2000,lang('code_2000'),$data);
    }

    public function list_engin_gofuer_cha(Request $request){
        $param = $request->post();
        $list = EnginModel::field('gofuer as value,gofuer as name')->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'status'=>1,'isturn'=>1])
            ->where('gofuer','neq','')->order('created_at DESC')->group('gofuer')->select()->toArray();
        $data['golist'] = $list;
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_gofuer_tong(Request $request){
        $param = $request->post();
        $daodt = date("Y-m-d");
        $engininfo = EnginModel::field('id,gofuer')->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'status'=>1,'isturn'=>1])
            ->where(['gofuer'=>$param['gofuer']])->select()->toArray();


        //计算负责人回款
        $hougongyumoney = (new HouService())->get_hou_gongyu_money($param['gofuer']);
        $hougongyukoufee = (new HouService())->get_hou_gongyu_koufee($param['gofuer']);
        $hougongzhimoneyqugoer = (new HouService())->get_hou_gongzhi_money_qugoer($param['gofuer']);
        $yujiedongkoufee = HouKouQifeiModel::alias('list')
            ->join('hou_gongyu hou','hou.id=list.zhuid')
            ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
            ->where(['list.type'=>2, 'hou.gofuer'=>$param['gofuer'],'isdong'=>1])
            ->sum('list.koufee');
        $hougongshuimoneygoquan = (new HouService())->get_hou_gongshui_money_goquan($param['gofuer']);
        $data['hougongyukeyong'] = round($hougongyumoney-$hougongyukoufee-$hougongzhimoneyqugoer+$yujiedongkoufee+$hougongshuimoneygoquan,2);


        $data['gofuerkeyong'] = 0;
        $data['hougonghuikeyong'] = 0;

        $data['daishou_all'] = 0;
        $data['daishou_fuwu'] = 0;
        $data['daishou_shuifei'] = 0;
        $data['daishou_gongjie'] = 0;
        $data['daishou_kuaifei'] = 0;

        foreach ($engininfo as $item){
            //计算工程回款
            $hougonghuimoney = (new HouService())->get_hou_gonghui_money($item['id']);
            $hougongzhimoneyquben = (new HouService())->get_hou_gongzhi_money_quben($item['id']);
            $hougonghuikoufee = (new HouService())->get_hou_gonghui_koufee($item['id']);
            $huijiedongkoufee = HouKouQifeiModel::alias('list')
                ->join('hou_gonghui hou','hou.id=list.zhuid')
                ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                ->where(['list.type'=>1, 'list.enginid'=>$item['id'],'isdong'=>1])
                ->sum('list.koufee');
            $data['hougonghuikeyong'] += round($hougonghuimoney - $hougongzhimoneyquben - $hougonghuikoufee + $huijiedongkoufee, 2);



            //计算待收 服务费
            $yingkoufee = 0;
            $shimoney = (new EnginService())->get_contract_shi_money($item['id']);
            $shijiemoney = (new EnginService())->get_contract_shi_jie_money($item['id']);
            $ratefu = ContractNeiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                ->where(['enginid'=>$item['id']])->order('id DESC')->value('ratefu');
            if($shijiemoney){
                $yingkoufee = round($shijiemoney*$ratefu/100, 2);
            }else{
                $yingkoufee = round($shimoney*$ratefu/100, 2);
            }
            $yikoufee = HouKouFuwuModel::alias('list')
                ->join('hou_gonghui hou','hou.id=list.zhuid')
                ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                ->where(['list.type'=>1,'list.enginid'=>$item['id']])
                ->sum('list.koufee');
            $yikoufee += HouKouFuwuModel::alias('list')
                ->join('hou_gongyu hou','hou.id=list.zhuid')
                ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                ->where(['list.type'=>2,'list.enginid'=>$item['id']])
                ->sum('list.koufee');
            $data['daishou_fuwu'] += round($yingkoufee - $yikoufee, 2);

            //计算待收 税款保证金及利息
            $shuiList = EnginShuiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                ->where(['enginid'=>$item['id']])->select()->toArray();
            foreach ($shuiList as $vvv){
                //是否在开票里面关联【并且开票日期不为空,】多个的话，取开票日期最小的数据
                $iskaipiao = PiaokaiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                    ->where(['enginid'=>$item['id'],'shuiid'=>$vvv['id'],'shuishou'=>2])
                    ->where("dt != '' and dt is not null and dt != '0000-00-00'")
                    ->order('dt ASC')->find();
                if(!$iskaipiao){
                    continue;
                }

                $yikouHui = HouKouShuifeiModel::alias('list')
                    ->join('hou_gonghui hou','hou.id=list.zhuid')
                    ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                    ->where(['list.type'=>1,'list.shuiid'=>$vvv['id']])
                    ->find();
                if($yikouHui){
                    continue;
                }
                $yikouYu = HouKouShuifeiModel::alias('list')
                    ->join('hou_gongyu hou','hou.id=list.zhuid')
                    ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                    ->where(['list.type'=>2,'list.shuiid'=>$vvv['id']])
                    ->find();
                if($yikouYu){
                    continue;
                }

                $vvv['shuiid'] = $vvv['id'];
                $vvv['shendt'] = date("Y-m-d", strtotime($vvv['created_at']));
                $vvv['dt'] = $iskaipiao['dt'];
                $jiqidt = getNextmonthFirstday($iskaipiao['dt']);

                //起息日：开票日期的下个月的1号，无开票日期则利息为0      结息日：到账日期,没有则取当前日期
                //税款保证金利息=周数 × 周息        周数=（计息期止-计息期起+1）/ 7，取整
                if($iskaipiao['dt'] && $iskaipiao['dt'] != '0000-00-00' && $jiqidt < $daodt){
                    $zhoushu = ceil(  (( strtotime($daodt) - strtotime($jiqidt) )/24/60/60 + 1) / 7 );
                    $data['daishou_shuifei'] += round($vvv['baofee']*$zhoushu*$vvv['ratexi']/100, 2);
                }
                $data['daishou_shuifei'] += $vvv['baofee'];
            }

            //计算待收 快递费
            $jiList = KuaiJiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                ->where(['isgua'=>'是','enginid'=>$item['id']])->select()->toArray();
            foreach ($jiList as $vvv){
                $yikouHui = HouKouKuaifeiModel::alias('list')
                    ->join('hou_gonghui hou','hou.id=list.zhuid')
                    ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                    ->where(['list.type'=>1,'list.kuaitype'=>1,'list.kuaiid'=>$vvv['id']])
                    ->find();
                if($yikouHui){
                    continue;
                }
                $yikouYu = HouKouKuaifeiModel::alias('list')
                    ->join('hou_gongyu hou','hou.id=list.zhuid')
                    ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                    ->where(['list.type'=>2,'list.kuaitype'=>1,'list.kuaiid'=>$vvv['id']])
                    ->find();
                if($yikouYu){
                    continue;
                }
                $data['daishou_kuaifei'] += $vvv['kuaifee'];
            }
            $shouList = KuaiShouModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                ->where(['isgua'=>'是','enginid'=>$item['id']])->select()->toArray();
            foreach ($shouList as $vvv){
                $yikouHui = HouKouKuaifeiModel::alias('list')
                    ->join('hou_gonghui hou','hou.id=list.zhuid')
                    ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                    ->where(['list.type'=>1,'list.kuaitype'=>2,'list.kuaiid'=>$vvv['id']])
                    ->find();
                if($yikouHui){
                    continue;
                }
                $yikouYu = HouKouKuaifeiModel::alias('list')
                    ->join('hou_gongyu hou','hou.id=list.zhuid')
                    ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                    ->where(['list.type'=>2,'list.kuaitype'=>2,'list.kuaiid'=>$vvv['id']])
                    ->find();
                if($yikouYu){
                    continue;
                }
                $data['daishou_kuaifei'] += $vvv['kuaifee'];
            }
        }


        //计算待收 工程负责人借款
        $jieList = HouJieModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
            ->where(['jieer'=>$param['gofuer']])->select()->toArray();
        foreach ($jieList as $item){
            $item = (new HouService())->get_jieshuju($item);
            $data['daishou_gongjie'] += $item['daihuanallfee'];
        }
        $data['daishou_gongjie'] = round($data['daishou_gongjie'],2);

        $data['gofuerkeyong'] = round($data['hougonghuikeyong'] + $data['hougongyukeyong'], 2);

        $data['daishou_fuwu'] = $data['daishou_fuwu'] < 0 ? 0 : $data['daishou_fuwu'];
        $data['daishou_shuifei'] = $data['daishou_fuwu'] < 0 ? 0 : $data['daishou_shuifei'];
        $data['daishou_gongjie'] = $data['daishou_fuwu'] < 0 ? 0 : $data['daishou_gongjie'];
        $data['daishou_kuaifei'] = $data['daishou_fuwu'] < 0 ? 0 : $data['daishou_kuaifei'];
        $data['daishou_all'] = round($data['daishou_fuwu'] + $data['daishou_shuifei']+ $data['daishou_gongjie']+ $data['daishou_kuaifei'], 2);


        $data['daodt'] = date("Y-m-d");
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_gofuer_lie(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];
        $where[] = ['e.isturn','=',1];
        $where[] = ['e.status','=',1];
        $where[] = ['e.gofuer','=',$param['gofuer']];

        $data['data'] = EnginModel::alias('e')
            ->field('e.*')
            ->where($where)
            ->order('e.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['qiandt'] = '';
                $item['shimoney'] = 0;
                $shiinfo = ContractShiModel::where(['comid'=>$this->userinfo['comid'],'enginid'=>$item['id'],'deleted_user'=>0,'isturn'=>1,'status'=>1])->find();
                if($shiinfo){
                    $item['qiandt'] = $shiinfo['qiandt'];
                    $item['shimoney'] = $shiinfo['money'];
                    $bumoney = ContractBuModel::where(['shiid'=>$shiinfo['id'],'deleted_user'=>0])->where(['status'=>1,'isturn'=>1])->sum('money');
                    $item['shimoney'] += $bumoney;
                }
                $item['shijiemoney'] = ContractShiJieModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                    ->where(['enginid'=>$item['id']])->sum('money');


                $item['piaokaifee'] = PiaoKaiListModel::alias('list')
                    ->join('piao_kai kai','kai.id=list.kaiid')
                    ->where(['kai.comid'=>$this->userinfo['comid'],'kai.deleted_user'=>0,'kai.isturn'=>1,'kai.status'=>1])
                    ->where(['kai.enginid'=>$item['id']])
                    ->sum('list.money');
                $item['piaokairatefee'] = PiaoKaiListModel::alias('list')
                    ->join('piao_kai kai','kai.id=list.kaiid')
                    ->where(['kai.comid'=>$this->userinfo['comid'],'kai.deleted_user'=>0,'kai.isturn'=>1,'kai.status'=>1])
                    ->where(['kai.enginid'=>$item['id']])
                    ->sum('list.ratefee');

                $item['gonghuimoney'] = (new HouService())->get_hou_gonghui_money($item['id']);

                $item['leihuibi'] = 0;
                if($item['shijiemoney'] > 0){
                    $item['leihuibi'] = round($item['gonghuimoney']/$item['shijiemoney']*100, 2);
                }else{
                    if($item['shimoney'] != 0){
                        $item['leihuibi'] = round($item['gonghuimoney']/$item['shimoney']*100, 2);
                    }
                }

                $item['nohuifee'] = 0;
                if($item['shijiemoney'] > 0){
                    $item['nohuifee'] = round($item['shijiemoney'] - $item['gonghuimoney'], 2);
                }else{
                    $item['nohuifee'] = round($item['shimoney'] - $item['gonghuimoney'], 2);
                }
                $item['nohuifee'] = $item['nohuifee'] < 0 ? 0 : $item['nohuifee'];

                $item['nohuibi'] = 0;
                if($item['shijiemoney'] > 0){
                    $item['nohuibi'] = round($item['nohuifee']/$item['shijiemoney']*100, 2);
                }else{
                    if($item['shimoney'] != 0){
                        $item['nohuibi'] = round($item['nohuifee']/$item['shimoney']*100, 2);
                    }
                }


                $item['koushuifee'] = HouKouShuifeiModel::alias('list')
                    ->leftJoin('hou_gonghui hui','hui.id=list.zhuid and list.type=1')
                    ->leftJoin('hou_gongyu yu','yu.id=list.zhuid and list.type=2')
                    ->join('engin_shui shui','shui.id=list.shuiid')
                    ->join('engin e','e.id=shui.enginid')
                    ->leftJoin('dept gui_unit','gui_unit.id=e.gui_unit')
                    ->where("hui.deleted_user = 0 or yu.deleted_user = 0")
                    ->where("hui.comid = ".$this->userinfo['comid']." or yu.comid = ".$this->userinfo['comid'])
                    ->where("hui.isturn = 1 or yu.isturn = 1")
                    ->where("hui.status in (0,1) or yu.isturn in (0,1)")
                    ->where(['shui.enginid'=>$item['id']])
                    ->sum('list.koufee');

                $item['koufuwufee'] = HouKouFuwuModel::alias('list')
                    ->leftJoin('hou_gonghui hui','hui.id=list.zhuid and list.type=1')
                    ->leftJoin('hou_gongyu yu','yu.id=list.zhuid and list.type=2')
                    ->join('engin e','e.id=list.enginid')
                    ->leftJoin('dept gui_unit','gui_unit.id=e.gui_unit')
                    ->where("hui.deleted_user = 0 or yu.deleted_user = 0")
                    ->where("hui.comid = ".$this->userinfo['comid']." or yu.comid = ".$this->userinfo['comid'])
                    ->where("hui.isturn = 1 or yu.isturn = 1")
                    ->where("hui.status in (0,1) or yu.isturn in (0,1)")
                    ->where(['list.enginid'=>$item['id']])
                    ->sum('list.koufee');

                $item['zhifuwufee'] = HouGongzhiListModel::alias('list')
                    ->leftJoin('hou_gongzhi zhi','zhi.id=list.gongzhiid')
                    ->join('engin e','e.id=zhi.enginid')
                    ->where(['zhi.comid'=>$this->userinfo['comid'],'zhi.deleted_user'=>0])
                    ->where(['zhi.isturn'=>1,'zhi.status'=>1])
                    ->where(['zhi.enginid'=>$item['id'],'list.zhikuanlei'=>9])
                    ->sum('list.money');

                $item['koukuaifee'] = HouKouKuaifeiModel::alias('list')
                    ->leftJoin('hou_gonghui hui','hui.id=list.zhuid and list.type=1')
                    ->leftJoin('hou_gongyu yu','yu.id=list.zhuid and list.type=2')
                    ->leftJoin('engin e','e.id=list.enginid')
                    ->leftJoin('dept gui_unit','gui_unit.id=e.gui_unit')
                    ->where("hui.deleted_user = 0 or yu.deleted_user = 0")
                    ->where("hui.comid = ".$this->userinfo['comid']." or yu.comid = ".$this->userinfo['comid'])
                    ->where("hui.isturn = 1 or yu.isturn = 1")
                    ->where("hui.status in (0,1) or yu.isturn in (0,1)")
                    ->where(['list.enginid'=>$item['id']])
                    ->sum('list.koufee');



                $item['kouqitafee'] = HouKouQifeiModel::alias('list')
                    ->leftJoin('hou_gonghui hui','hui.id=list.zhuid and list.type=1')
                    ->leftJoin('hou_gongyu yu','yu.id=list.zhuid and list.type=2')
                    ->leftJoin('engin e','e.id=list.enginid')
                    ->leftJoin('dept gui_unit','gui_unit.id=e.gui_unit')
                    ->where("hui.deleted_user = 0 or yu.deleted_user = 0")
                    ->where("hui.comid = ".$this->userinfo['comid']." or yu.comid = ".$this->userinfo['comid'])
                    ->where("hui.isturn = 1 or yu.isturn = 1")
                    ->where("hui.status in (0,1) or yu.isturn in (0,1)")
                    ->where(['list.enginid'=>$item['id']])
                    ->sum('list.koufee');

                $item['piaoshoumoney'] = PiaoShouModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                    ->where(['enginid'=>$item['id']])->sum('money');
                $item['piaoshouratefee'] = PiaoShouModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                    ->where(['enginid'=>$item['id']])->sum('ratefee');

                $item['hougongshuimoney'] = HouGongshuiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                    ->where(['enginid'=>$item['id']])->sum('money');

                $item['nodishuifei'] = round($item['piaoshouratefee'] - $item['hougongshuimoney'], 2);

                $item['yizhifee'] = HouGongzhiListModel::alias('list')
                    ->join('hou_gongzhi zhi','zhi.id=list.gongzhiid')
                    ->where(['zhi.comid'=>$this->userinfo['comid'],'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
                    ->where(['zhi.enginid'=>$item['id'],'list.fuer'=>$item['gofuer']])
                    ->sum('list.money');

                return $item;
            })->toArray();

        return outputJson(2000,lang('code_2000'),$data);
    }

    public function list_engin_quan(Request $request){
        $param = $request->post();

        $data['year'] = (new ContractService())->get_quanyear();
        $data['chanid'] = (new UserService())->get_chaninfo_all();
        $data['jidu'] = [
            0=>'全年',
            1=>'一季度',
            2=>'二季度',
            3=>'三季度',
            4=>'四季度',
        ];


        if($param['qingci'] == 1){
            $param['year'] = date("Y");
            $param['jidu'] = 0;
            $param['chanid'] = $data['chanid'][0]['value'];
        }
        if(!isset($param['chanid']) || empty($param['chanid'])){
            $param['chanid'] = $data['chanid'][0]['value'];
        }


        $data['is_year'] = isset($param['year']) ? $param['year'] : '';
        $data['is_jidu'] = isset($param['jidu']) ? $param['jidu'] : '';
        $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';


        $where = [];
        $where[] = ['zhu.deleted_user','=', 0];
        $where[] = ['zhu.comid','=',$this->userinfo['comid']];
        $where[] = ['zhu.isturn','=',1];
        $where[] = ['zhu.status','=',1];

        $whereGui[] = ['zhu.gui_unit','=',$param['chanid']];
        $whereGuit[] = ['e.gui_unit','=',$param['chanid']];


        //修改规则：原则上是  选择 山西天乾科技有限公司 的时候，应该是统计不区分分公司的所有数据。现在仅出来业务归属是 山西天乾科技有限公司 的数据
        if($param['chanid'] == 1){
            $whereGui = [];
            $whereGuit = [];
        }



        $where1 = "";
        $where2 = "";
        $where3 = "";
        $where4 = "";
        $where5 = "";
        $where6 = "";
        $where7 = "";
        if(isset($param['year']) && $param['year'] > 0){
            if(isset($param['jidu']) && $param['jidu'] > 0){
                if($param['jidu'] == 1){
                    $where1 = "zhu.windt >= '".$param['year']."-01-01' and zhu.windt <= '".$param['year']."-03-31'";
                    $where2 = "zhu.qiandt >= '".$param['year']."-01-01' and zhu.qiandt <= '".$param['year']."-03-31'";
                    $where3 = "zhu.jiedt >= '".$param['year']."-01-01' and zhu.jiedt <= '".$param['year']."-03-31'";
                    $where4 = "zhu.dt >= '".$param['year']."-01-01' and zhu.dt <= '".$param['year']."-03-31'";
                    $where5 = "zhu.dt >= '".$param['year']."-01-01' and zhu.dt <= '".$param['year']."-03-31'";
                    $where6 = "zhu.dt >= '".$param['year']."-01-01' and zhu.dt <= '".$param['year']."-03-31'";
                    $where7 = "zhu.dt >= '".$param['year']."-01-01' and zhu.dt <= '".$param['year']."-03-31'";
                }
                if($param['jidu'] == 2){
                    $where1 = "zhu.windt >= '".$param['year']."-04-01' and zhu.windt <= '".$param['year']."-06-30'";
                    $where2 = "zhu.qiandt >= '".$param['year']."-04-01' and zhu.qiandt <= '".$param['year']."-06-30'";
                    $where3 = "zhu.jiedt >= '".$param['year']."-04-01' and zhu.jiedt <= '".$param['year']."-06-30'";
                    $where4 = "zhu.dt >= '".$param['year']."-04-01' and zhu.dt <= '".$param['year']."-06-30'";
                    $where5 = "zhu.dt >= '".$param['year']."-04-01' and zhu.dt <= '".$param['year']."-06-30'";
                    $where6 = "zhu.dt >= '".$param['year']."-04-01' and zhu.dt <= '".$param['year']."-06-30'";
                    $where7 = "zhu.dt >= '".$param['year']."-04-01' and zhu.dt <= '".$param['year']."-06-30'";
                }
                if($param['jidu'] == 3){
                    $where1 = "zhu.windt >= '".$param['year']."-07-01' and zhu.windt <= '".$param['year']."-09-30'";
                    $where2 = "zhu.qiandt >= '".$param['year']."-07-01' and zhu.qiandt <= '".$param['year']."-09-30'";
                    $where3 = "zhu.jiedt >= '".$param['year']."-07-01' and zhu.jiedt <= '".$param['year']."-09-30'";
                    $where4 = "zhu.dt >= '".$param['year']."-07-01' and zhu.dt <= '".$param['year']."-09-30'";
                    $where5 = "zhu.dt >= '".$param['year']."-07-01' and zhu.dt <= '".$param['year']."-09-30'";
                    $where6 = "zhu.dt >= '".$param['year']."-07-01' and zhu.dt <= '".$param['year']."-09-30'";
                    $where7 = "zhu.dt >= '".$param['year']."-07-01' and zhu.dt <= '".$param['year']."-09-30'";
                }
                if($param['jidu'] == 4){
                    $where1 = "zhu.windt >= '".$param['year']."-10-01' and zhu.windt <= '".$param['year']."-12-31'";
                    $where2 = "zhu.qiandt >= '".$param['year']."-10-01' and zhu.qiandt <= '".$param['year']."-12-31'";
                    $where3 = "zhu.jiedt >= '".$param['year']."-10-01' and zhu.jiedt <= '".$param['year']."-12-31'";
                    $where4 = "zhu.dt >= '".$param['year']."-10-01' and zhu.dt <= '".$param['year']."-12-31'";
                    $where5 = "zhu.dt >= '".$param['year']."-10-01' and zhu.dt <= '".$param['year']."-12-31'";
                    $where6 = "zhu.dt >= '".$param['year']."-10-01' and zhu.dt <= '".$param['year']."-12-31'";
                    $where7 = "zhu.dt >= '".$param['year']."-10-01' and zhu.dt <= '".$param['year']."-12-31'";
                }
            }else{
                $where1 = "zhu.windt >= '".$param['year']."-01-01' and zhu.windt <= '".$param['year']."-12-31'";
                $where2 = "zhu.qiandt >= '".$param['year']."-01-01' and zhu.qiandt <= '".$param['year']."-12-31'";
                $where3 = "zhu.jiedt >= '".$param['year']."-01-01' and zhu.jiedt <= '".$param['year']."-12-31'";
                $where4 = "zhu.dt >= '".$param['year']."-01-01' and zhu.dt <= '".$param['year']."-12-31'";
                $where5 = "zhu.dt >= '".$param['year']."-01-01' and zhu.dt <= '".$param['year']."-12-31'";
                $where6 = "zhu.dt >= '".$param['year']."-01-01' and zhu.dt <= '".$param['year']."-12-31'";
                $where7 = "zhu.dt >= '".$param['year']."-01-01' and zhu.dt <= '".$param['year']."-12-31'";
            }
        }


        $data['enginnum'] = EnginModel::alias('zhu')->where($where)->where($whereGui)->where($where1)->count();
        $data['shimoney'] = ContractShiModel::alias('zhu')
            ->join('engin e', 'e.id=zhu.enginid')->where($whereGuit)
            ->where($where)->where($where2)->sum('zhu.money');

        $data['shijiemoney'] = ContractShiJieModel::alias('zhu')
            ->join('engin e', 'e.id=zhu.enginid')->where($whereGuit)
            ->where($where)->where($where3)->sum('zhu.money');

        $data['piaokaifee'] = PiaoKaiListModel::alias('list')
            ->join('piao_kai zhu','zhu.id=list.kaiid')
            ->join('engin e', 'e.id=zhu.enginid')->where($whereGuit)
            ->where($where)->where($where4)
            ->sum('list.money');

        $data['huihonghuimoney'] = HouGonghuiModel::alias('zhu')
            ->join('engin e', 'e.id=zhu.enginid')->where($whereGuit)
            ->where($where)->where($where5)->sum('zhu.money');

        $data['koushuifee'] = HouKouShuifeiModel::alias('list')
            ->leftJoin('hou_gonghui zhu','zhu.id=list.zhuid')
            ->join('engin e', 'e.id=zhu.enginid')->where($whereGuit)
            ->where(['list.type'=>1])
            ->where($where)->where($where6)
            ->sum('list.koufee');

        $data['koushuifee'] += HouKouShuifeiModel::alias('list')
            ->leftJoin('hou_gongyu zhu','zhu.id=list.zhuid')
            ->where(['list.type'=>2])
            ->where($where)->where($where6)
            ->sum('list.koufee');

        $data['koufuwufee'] = HouKouFuwuModel::alias('list')
            ->leftJoin('hou_gonghui zhu','zhu.id=list.zhuid')
            ->join('engin e', 'e.id=zhu.enginid')->where($whereGuit)
            ->where(['list.type'=>1])
            ->where($where)->where($where7)
            ->sum('list.koufee');

        $data['koufuwufee'] += HouKouFuwuModel::alias('list')
            ->leftJoin('hou_gongyu zhu','zhu.id=list.zhuid')
            ->where(['list.type'=>2])
            ->where($where)->where($where7)
            ->sum('list.koufee');




        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_quan_chan(Request $request){
        $param = $request->post();

        if($param['qingci'] == 1){
            $param['year'] = date("Y");
            $param['jidu'] = 0;
        }

        $where1 = [];
        if(isset($param['year']) && $param['year'] > 0){
            if(isset($param['jidu']) && $param['jidu'] > 0){
                if($param['jidu'] == 1){
                    $where1 = "dt >= '".$param['year']."-01-01' and dt <= '".$param['year']."-03-31'";
                }
                if($param['jidu'] == 2){
                    $where1 = "dt >= '".$param['year']."-04-01' and dt <= '".$param['year']."-06-30'";
                }
                if($param['jidu'] == 3){
                    $where1 = "dt >= '".$param['year']."-07-01' and dt <= '".$param['year']."-09-30'";
                }
                if($param['jidu'] == 4){
                    $where1 = "dt >= '".$param['year']."-10-01' and dt <= '".$param['year']."-12-31'";
                }
            }else{
                $where1 = "dt >= '".$param['year']."-01-01' and dt <= '".$param['year']."-12-31'";
            }
        }

        $data['data'] = HouGonghuiModel::field('sum(money) as countfee,enginid')
            ->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0])
            ->where(['isturn'=>1,'status'=>1])
            ->where($where1)
            ->group('enginid')
            ->order('countfee DESC')
            ->limit(10)
            ->select()->toArray();
        foreach ($data['data'] as &$item){
            $engininfo = EnginModel::where(['id'=>$item['enginid']])->find();
            $item['enginname'] = $engininfo['name'];
            $item['gofuer'] = $engininfo['gofuer'];
        }

        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_quan_cheng(Request $request){
        $param = $request->post();

        if($param['qingci'] == 1){
            $param['year'] = date("Y");
            $param['jidu'] = 0;
        }

        $where1 = [];
        if(isset($param['year']) && $param['year'] > 0){
            if(isset($param['jidu']) && $param['jidu'] > 0){
                if($param['jidu'] == 1){
                    $where1 = "windt >= '".$param['year']."-01-01' and windt <= '".$param['year']."-03-31'";
                }
                if($param['jidu'] == 2){
                    $where1 = "windt >= '".$param['year']."-04-01' and windt <= '".$param['year']."-06-30'";
                }
                if($param['jidu'] == 3){
                    $where1 = "windt >= '".$param['year']."-07-01' and windt <= '".$param['year']."-09-30'";
                }
                if($param['jidu'] == 4){
                    $where1 = "windt >= '".$param['year']."-10-01' and windt <= '".$param['year']."-12-31'";
                }
            }else{
                $where1 = "windt >= '".$param['year']."-01-01' and windt <= '".$param['year']."-12-31'";
            }
        }


        $data['data'] = EnginModel::field('sum(winfee) as countfee,count(id) as nums,gofuer')
            ->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0])
            ->where(['isturn'=>1,'status'=>1])
            ->where('gofuer','neq','')
            ->where($where1)
            ->group('gofuer')
            ->order('countfee DESC')
            ->limit(10)
            ->select()->toArray();


        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_quan_jie(Request $request){
        $param = $request->post();

        if($param['qingci'] == 1){
            $param['year'] = date("Y");
            $param['jidu'] = 0;
        }

        $where1 = [];
        if(isset($param['year']) && $param['year'] > 0){
            if(isset($param['jidu']) && $param['jidu'] > 0){
                if($param['jidu'] == 1){
                    $where1 = "windt >= '".$param['year']."-01-01' and windt <= '".$param['year']."-03-31'";
                }
                if($param['jidu'] == 2){
                    $where1 = "windt >= '".$param['year']."-04-01' and windt <= '".$param['year']."-06-30'";
                }
                if($param['jidu'] == 3){
                    $where1 = "windt >= '".$param['year']."-07-01' and windt <= '".$param['year']."-09-30'";
                }
                if($param['jidu'] == 4){
                    $where1 = "windt >= '".$param['year']."-10-01' and windt <= '".$param['year']."-12-31'";
                }
            }else{
                $where1 = "windt >= '".$param['year']."-01-01' and windt <= '".$param['year']."-12-31'";
            }
        }

        $data['data'] = HouJieModel::field('jieer, sum(money) as countfee')
            ->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0])
            ->where(['isturn'=>1,'status'=>1])
            ->where('jieer','neq','')
            ->group('jieer')
            ->order('countfee DESC')
            ->select()->toArray();

        foreach ($data['data'] as &$item){
            $item['yinghuanbenfee'] = 0;
            $item['yihuanbenfee'] = 0;
            $item['yihuanlifee'] = 0;
            $item['daihuanbenfee'] = 0;

            $info = HouJieModel::field('*')
                ->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0])
                ->where(['isturn'=>1,'status'=>1])
                ->where(['jieer'=>$item['jieer']])
                ->select()->toArray();
            foreach ($info as $k=>$v){
                $v = (new HouService())->get_jieshuju($v);
                $item['yinghuanbenfee'] += $v['yinghuanbenfee'];
                $item['yihuanbenfee'] += $v['yihuanbenfee'];
                $item['yihuanlifee'] += $v['yihuanlifee'];
                $item['daihuanbenfee'] += $v['daihuanbenfee'];
            }

            $item['yinghuanbenfee'] = round($item['yinghuanbenfee'], 2);
            $item['yihuanbenfee'] = round($item['yihuanbenfee'], 2);
            $item['yihuanlifee'] = round($item['yihuanlifee'], 2);
            $item['daihuanbenfee'] = round($item['daihuanbenfee'], 2);
        }


        return outputJson(2000,lang('code_2000'),$data);
    }


    public function list_engin_dong(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];
        $where[] = ['e.isturn','=',1];
        $where[] = ['e.status','=',1];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name|e.number|e.jiaer|e.gofuer','like', '%'.$param['keyword'].'%'];
        }

        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['e.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['e.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['jiaer']) && !empty($param['jiaer'])){
            $where[] = ['e.jiaer','like', '%'.$param['jiaer'].'%'];
        }
        if(isset($param['gofuer']) && !empty($param['gofuer'])){
            $where[] = ['e.gofuer','like', '%'.$param['gofuer'].'%'];
        }
        if(isset($param['state']) && !empty($param['state'])){
            $where[] = ['e.state','=', $param['state']];
        }
        $data['state'] = (new EnginService())->get_engin_state();
        $data['is_state'] = isset($param['state']) ? $param['state'] : '';

        $data['data'] = EnginModel::alias('e')
            ->field('e.*,win_unit.name as win_unit_name,gui_unit.name as gui_unit_name')
            ->leftJoin('dept win_unit','win_unit.id=e.win_unit')
            ->leftJoin('dept gui_unit','gui_unit.id=e.gui_unit')
            ->where($where)
            ->where((new MenuService())->get_miss_where('engin', 'e'))
            ->order('e.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['state_name'] = (new EnginService())->get_engin_state_name($item);


                $item['shiinfo'] = ContractShiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])->where(['enginid'=>$item['id']])->find();
                $item['shimoney'] = (new EnginService())->get_contract_shi_money($item['id']);
                $item['shijiemoney'] = (new EnginService())->get_contract_shi_jie_money($item['id']);

                $item['gongzhimoneygogong'] = (new HouService())->get_hou_gongzhi_money_gogong($item['id']);
                $item['fei_cai'] = HouGongzhiListModel::alias('list')
                    ->join('hou_gongzhi zhi','zhi.id=list.gongzhiid')
                    ->join('dealcom deal','deal.name=list.fuer')
                    ->where(['zhi.comid'=>$this->userinfo['comid'],'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
                    ->where(['zhi.enginid'=>$item['id'],'deal.type'=>3,'list.zhikuanlei'=>1])
                    ->sum('list.money');
                $item['fei_lao'] = HouGongzhiListModel::alias('list')
                    ->join('hou_gongzhi zhi','zhi.id=list.gongzhiid')
                    ->join('dealcom deal','deal.name=list.fuer')
                    ->where(['zhi.comid'=>$this->userinfo['comid'],'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
                    ->where(['zhi.enginid'=>$item['id'],'deal.type'=>3,'list.zhikuanlei'=>2])
                    ->sum('list.money');
                $item['fei_zu'] = HouGongzhiListModel::alias('list')
                    ->join('hou_gongzhi zhi','zhi.id=list.gongzhiid')
                    ->join('dealcom deal','deal.name=list.fuer')
                    ->where(['zhi.comid'=>$this->userinfo['comid'],'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
                    ->where(['zhi.enginid'=>$item['id'],'deal.type'=>3,'list.zhikuanlei'=>3])
                    ->sum('list.money');
                $item['fei_fen'] = HouGongzhiListModel::alias('list')
                    ->join('hou_gongzhi zhi','zhi.id=list.gongzhiid')
                    ->join('dealcom deal','deal.name=list.fuer')
                    ->where(['zhi.comid'=>$this->userinfo['comid'],'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
                    ->where(['zhi.enginid'=>$item['id'],'deal.type'=>3,'list.zhikuanlei'=>4])
                    ->sum('list.money');
                $item['fei_qi'] = round($item['gongzhimoneygogong'] - $item['fei_cai'] - $item['fei_lao'] - $item['fei_zu'] - $item['fei_fen'], 2);

                $item['shi_cai'] = 0;
                $item['shi_lao'] = 0;
                $item['shi_zu'] = 0;
                $item['shi_fen'] = 0;
                $item['shi_qi'] = 0;
                if($item['shimoney'] > 0){
                    $item['shi_cai'] = round($item['fei_cai']/$item['shimoney']*100, 2);
                    $item['shi_lao'] = round($item['fei_lao']/$item['shimoney']*100, 2);
                    $item['shi_zu'] = round($item['fei_zu']/$item['shimoney']*100, 2);
                    $item['shi_fen'] = round($item['fei_fen']/$item['shimoney']*100, 2);
                    $item['shi_qi'] = round($item['fei_qi']/$item['shimoney']*100, 2);
                }else{
                    if($item['shijiemoney'] > 0){
                        $item['shi_cai'] = round($item['fei_cai']/$item['shijiemoney']*100, 2);
                        $item['shi_lao'] = round($item['fei_lao']/$item['shijiemoney']*100, 2);
                        $item['shi_zu'] = round($item['fei_zu']/$item['shijiemoney']*100, 2);
                        $item['shi_fen'] = round($item['fei_fen']/$item['shijiemoney']*100, 2);
                        $item['shi_qi'] = round($item['fei_qi']/$item['shijiemoney']*100, 2);
                    }
                }


                return $item;
            })->toArray();

        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_feishouhui(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];
        $where[] = ['e.isturn','=',1];
        $where[] = ['e.status','=',1];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name|e.gofuer','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['e.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['gofuer']) && !empty($param['gofuer'])){
            $where[] = ['e.gofuer','like', '%'.$param['gofuer'].'%'];
        }
        if(isset($param['gui_unit']) && !empty($param['gui_unit'])){
            $where[] = ['gui_unit.id','=', $param['gui_unit']];
        }

        $data['gui_unit'] = (new UserService())->get_chaninfo_all();
        $data['is_gui_unit'] = isset($param['gui_unit']) ? $param['gui_unit'] : '';


        $data['data'] = EnginModel::alias('e')
            ->field('e.*,gui_unit.name as gui_unit_name')
            ->leftJoin('dept gui_unit','gui_unit.id=e.gui_unit')
            ->where($where)
            ->where((new MenuService())->get_miss_where('engin', 'e'))
            ->order('e.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['shiinfo'] = ContractShiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])->where(['enginid'=>$item['id']])->find();
                $item['shimoney'] = (new EnginService())->get_contract_shi_money($item['id']);
                $item['shijiemoney'] = (new EnginService())->get_contract_shi_jie_money($item['id']);

                $item['ratefu'] = ContractNeiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                    ->where(['enginid'=>$item['id']])->order('id DESC')->value('ratefu');
                $item['rateshui'] = ContractNeiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                    ->where(['enginid'=>$item['id']])->order('id DESC')->value('rateshui');

                $item['yingkoufee'] = 0;
                if($item['shijiemoney']){
                    $item['yingkoufee'] = round($item['shijiemoney']*$item['ratefu']/100, 2);
                }else{
                    $item['yingkoufee'] = round($item['shimoney']*$item['ratefu']/100, 2);
                }

                $item['yikoufee'] = HouKouFuwuModel::alias('list')
                    ->join('hou_gonghui hou','hou.id=list.zhuid')
                    ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                    ->where(['list.type'=>1,'list.enginid'=>$item['id']])
                    ->sum('list.koufee');
                $item['yikoufee'] += HouKouFuwuModel::alias('list')
                    ->join('hou_gongyu hou','hou.id=list.zhuid')
                    ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                    ->where(['list.type'=>2,'list.enginid'=>$item['id']])
                    ->sum('list.koufee');
                $item['daikoufee'] = round($item['yingkoufee'] - $item['yikoufee'], 2);


                $piaokaimoney = PiaokaiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                    ->where(['enginid'=>$item['id']])->sum('money');
                $item['shuiyingfee'] = round($piaokaimoney*$item['rateshui']/100, 2);

                $item['shuiyifee'] = HouKouShuifeiModel::alias('list')
                    ->join('hou_gonghui hou','hou.id=list.zhuid')
                    ->join('engin_shui shui','shui.id=list.shuiid')
                    ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                    ->where(['list.type'=>1,'shui.enginid'=>$item['id']])
                    ->sum('list.koufee');
                $item['shuiyifee'] += HouKouShuifeiModel::alias('list')
                    ->join('hou_gongyu hou','hou.id=list.zhuid')
                    ->join('engin_shui shui','shui.id=list.shuiid')
                    ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                    ->where(['list.type'=>2,'shui.enginid'=>$item['id']])
                    ->sum('list.koufee');

                $item['shuiyizhifee'] = HouKouQifeiModel::alias('list')
                    ->join('hou_gonghui hou','hou.id=list.zhuid')
                    ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                    ->where(['list.type'=>1,'list.houkoulei'=>2,'list.enginid'=>$item['id']])
                    ->sum('list.koufee');
                $item['shuiyizhifee'] += HouKouQifeiModel::alias('list')
                    ->join('hou_gongyu hou','hou.id=list.zhuid')
                    ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                    ->where(['list.type'=>2,'list.houkoulei'=>2,'list.enginid'=>$item['id']])
                    ->sum('list.koufee');

                //外管税缴纳金额(元)
                //取值：销项票开具中，审核通过的，开具跨区域涉税事项表字段为 是，外管税缴纳方式为 工程负责人自行支付 的 工程所在地本次已交外管税(元)
                $item['waifee'] = PiaokaiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0])
                    ->where(['isturn'=>1,'status'=>1,'enginid'=>$item['id']])
                    ->where(['iskaishe'=>'是','waijiao'=>'工程负责人自行支付'])
                    ->sum('waifee');



//                $item['shuidaifee'] = round($item['shuiyingfee'] - $item['shuiyifee'] - $item['shuiyizhifee'], 2);
//                $item['shuidaifee'] = round($item['shuiyingfee'] - $item['shuiyifee'], 2);
//                $item['shuidaifee'] = round($item['shuiyingfee'] - $item['shuiyifee'] - $item['shuiyizhifee'], 2);
                $item['shuidaifee'] = round($item['shuiyingfee'] - $item['shuiyifee'] - $item['shuiyizhifee']- $item['waifee'], 2);


                $item['qiyifee'] = HouKouQifeiModel::alias('list')
                    ->join('hou_gonghui hou','hou.id=list.zhuid')
                    ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                    ->where(['list.type'=>1,'list.enginid'=>$item['id']])
                    ->sum('list.koufee');
                $item['qiyifee'] += HouKouQifeiModel::alias('list')
                    ->join('hou_gongyu hou','hou.id=list.zhuid')
                    ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                    ->where(['list.type'=>2,'list.enginid'=>$item['id']])
                    ->sum('list.koufee');


//                $item['shouallfee'] = round($item['yikoufee'] + $item['shuiyifee'] + $item['shuiyizhifee'] + $item['qiyifee'], 2);
                $item['shouallfee'] = round($item['yikoufee'] + $item['shuiyifee'] + $item['qiyifee'], 2);
                $item['daiallfee'] = round($item['daikoufee'] + $item['shuidaifee'], 2);

                return $item;
            })->toArray();

        return outputJson(2000,lang('code_2000'),$data);
    }

    public function list_engin_deal_tai(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['deal.deleted_user','=', 0];
        $where[] = ['deal.comid','=',$this->userinfo['comid']];
        $where[] = ['deal.isturn','=',1];
        $where[] = ['deal.status','=',1];
        $where[] = ['deal.type','=',3];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['deal.name','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['deal.name','like', '%'.$param['name'].'%'];
        }

        $list = [];
        $data['data'] = DealcomModel::alias('deal')
            ->field('deal.id,deal.name')
            ->where($where)
            ->order('deal.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                return $item;
            })->toArray();

        foreach ($data['data']['data'] as $item){
            $enginList = [];

            //累计支付销售方
            $hougongzhi = HouGongzhiListModel::alias('list')
                ->field('zhi.enginid,sum(list.money) as hougongzhifee,e.name as enginname')
                ->join('hou_gongzhi zhi','zhi.id=list.gongzhiid')
                ->join('engin e','e.id=zhi.enginid')
                ->where(['zhi.comid'=>$this->userinfo['comid'],'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
                ->where(['list.fuer'=>$item['name']])
                ->group('zhi.enginid')
                ->select()->toArray();
            foreach ($hougongzhi as $hougongzhi_VV){
                $enginList[$hougongzhi_VV['enginid']] = $hougongzhi_VV;
            }


            //销售方进项票累计
            $piaoshou = PiaoShouListModel::alias('list')
                ->field('shou.enginid,sum(list.money) as piaoshoufee,sum(list.ratefee) as piaoshouratefee,e.name as enginname')
                ->join('piao_shou shou','shou.id=list.shouid')
                ->join('engin e','e.id=shou.enginid')
                ->where(['shou.comid'=>$this->userinfo['comid'],'shou.deleted_user'=>0,'shou.isturn'=>1,'shou.status'=>1])
                ->where(['list.xiaoer'=>$item['name']])
                ->group('shou.enginid')
                ->select()->toArray();
            foreach ($piaoshou as $piaoshou_VV){
                if(isset($enginList[$piaoshou_VV['enginid']])){
                    $enginList[$piaoshou_VV['enginid']]['piaoshoufee'] = $piaoshou_VV['piaoshoufee'];
                    $enginList[$piaoshou_VV['enginid']]['piaoshouratefee'] = $piaoshou_VV['piaoshouratefee'];
                }else{
                    $enginList[$piaoshou_VV['enginid']] = $piaoshou_VV;
                }
            }


            //销售方可签采购合同金额
            foreach ($enginList as &$en_VV){
                if(isset($en_VV['hougongzhifee']) && isset($en_VV['piaoshoufee'])){
                    $en_VV['keqiancai'] = $en_VV['hougongzhifee'] > $en_VV['piaoshoufee'] ? $en_VV['piaoshoufee'] : $en_VV['hougongzhifee'];
                }
            }


            //销售方已签采购合同金额
            $contractcai = ContractCaiModel::alias('cai')
                ->field('cai.enginid,e.name as enginname')
                ->join('engin e','e.id=cai.enginid')
                ->where(['cai.comid'=>$this->userinfo['comid'],'cai.deleted_user'=>0,'cai.isturn'=>1,'cai.status'=>1])
                ->where(['cai.gonger'=>$item['name']])
                ->group('cai.enginid')
                ->select()->toArray();
            foreach ($contractcai as $contractcai_VV){
                $contractcai_VV['yiqiancai'] = 0;
                $caiinfo = ContractCaiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                    ->where(['enginid'=>$contractcai_VV['enginid'],'gonger'=>$item['name']])->select()->toArray();
                foreach ($caiinfo as $caivvvvv){
                    $existJieMoney = ContractCaiJieModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                        ->where(['enginid'=>$contractcai_VV['enginid'],'caiid'=>$caivvvvv['id']])->sum('money');
                    if($existJieMoney){
                        $contractcai_VV['yiqiancai'] += $existJieMoney;
                    }else{
                        $contractcai_VV['yiqiancai'] += $caivvvvv['money'];
                    }
                }

                if(isset($enginList[$contractcai_VV['enginid']])){
                    $enginList[$contractcai_VV['enginid']]['yiqiancai'] = $contractcai_VV['yiqiancai'];
                }else{
                    $enginList[$contractcai_VV['enginid']] = $contractcai_VV;
                }
            }


            //销售方待签采购合同金额
            foreach ($enginList as $en22_KK => $en22_VV){
                if(!isset($en22_VV['keqiancai'])){
                    $en22_VV['keqiancai'] = 0;
                }
                if(!isset($en22_VV['yiqiancai'])){
                    $en22_VV['yiqiancai'] = 0;
                }
                $en22_VV['daiqiancai'] = round($en22_VV['keqiancai'] - $en22_VV['yiqiancai'], 2);
                $en22_VV['daiqiancai'] = $en22_VV['daiqiancai'] < 0 ? 0 : $en22_VV['daiqiancai'];
                if($en22_VV['daiqiancai']){
                    $enginList[$en22_KK]['daiqiancai'] = $en22_VV['daiqiancai'];
                }
            }


            //可抵扣进项票金额
            foreach ($enginList as &$en33_VV){
                if(isset($en33_VV['hougongzhifee']) && $en33_VV['hougongzhifee'] > 0
                    && isset($en33_VV['piaoshoufee']) && $en33_VV['piaoshoufee'] > 0
                    && isset($en33_VV['keqiancai']) && $en33_VV['keqiancai'] > 0) {
                    $en33_VV['kedijin'] = $en33_VV['hougongzhifee'] > $en33_VV['piaoshoufee'] ? $en33_VV['piaoshoufee'] : $en33_VV['hougongzhifee'];
                }
            }


            //已抵扣进项票价税合计
            $hougongshui = HouGongshuiListModel::alias('list')
                ->field('shui.enginid,sum(list.money) as yidijin,e.name as enginname')
                ->join('hou_gongshui shui','shui.id=list.gongshuiid')
                ->join('engin e','e.id=shui.enginid')
                ->where(['shui.comid'=>$this->userinfo['comid'],'shui.deleted_user'=>0,'shui.isturn'=>1,'shui.status'=>1])
                ->where(['list.xiaoer'=>$item['name']])
                ->group('shui.enginid')
                ->select()->toArray();
            foreach ($hougongshui as $hougongshui_VV){
                if(isset($enginList[$hougongshui_VV['enginid']])){
                    $enginList[$hougongshui_VV['enginid']]['yidijin'] = $hougongshui_VV['yidijin'];
                }else{
                    $enginList[$hougongshui_VV['enginid']] = $hougongshui_VV;
                }
            }

            //已抵扣退税
            $hougongshui22 = HouGongshuiListModel::alias('list')
                ->field('shui.enginid,sum(list.ratefee) as yidirate,e.name as enginname')
                ->join('hou_gongshui shui','shui.id=list.gongshuiid')
                ->join('engin e','e.id=shui.enginid')
                ->where(['shui.comid'=>$this->userinfo['comid'],'shui.deleted_user'=>0,'shui.isturn'=>1,'shui.status'=>1])
                ->where(['list.xiaoer'=>$item['name']])
                ->group('shui.enginid')
                ->select()->toArray();
            foreach ($hougongshui22 as $hougongshui22_VV){
                if(isset($enginList[$hougongshui22_VV['enginid']])){
                    $enginList[$hougongshui22_VV['enginid']]['yidirate'] = $hougongshui22_VV['yidirate'];
                }else{
                    $enginList[$hougongshui22_VV['enginid']] = $hougongshui22_VV;
                }
            }


            //剩余可抵扣进项票金额
            foreach ($enginList as $en4444_KK => $en4444_VV){
                if(!isset($en4444_VV['kedijin'])){
                    $en4444_VV['kedijin'] = 0;
                }
                if(!isset($en4444_VV['yidijin'])){
                    $en4444_VV['yidijin'] = 0;
                }
                $en4444_VV['shengdijin'] = round($en4444_VV['kedijin'] - $en4444_VV['yidijin'], 2);
                $en4444_VV['shengdijin'] = $en4444_VV['shengdijin'] < 0 ? 0 : $en4444_VV['shengdijin'];
                if($en4444_VV['shengdijin']){
                    $enginList[$en4444_KK]['shengdijin'] = $en4444_VV['shengdijin'];
                }
            }






            if($enginList){
                foreach ($enginList as $enginList_VV){
                    $enginList_VV['name'] = $item['name'];
                    $list[] = $enginList_VV;
                }
            }else{
                $list[] = ['name'=>$item['name']];
            }
        }


        foreach ($list as &$mmm){
            if(isset($mmm['enginid'])){
                $mmm['shencai'] = ContractCaiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>0])
                    ->where(['enginid'=>$mmm['enginid'],'gonger'=>$mmm['name']])->sum('money');
            }
        }


        $data['data']['data'] = $list;
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_deal_tai222(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['deal.deleted_user','=', 0];
        $where[] = ['deal.comid','=',$this->userinfo['comid']];
        $where[] = ['deal.isturn','=',1];
        $where[] = ['deal.status','=',1];
        $where[] = ['deal.type','=',3];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['deal.name','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['deal.name','like', '%'.$param['name'].'%'];
        }

        $list = [];
        $deal = DealcomModel::alias('deal')
            ->field('deal.id,deal.name')
            ->where($where)
            ->order('deal.id DESC')
            ->select()->toArray();
        foreach ($deal as $item){
            $enginList = [];

            //累计支付销售方
            $hougongzhi = HouGongzhiListModel::alias('list')
                ->field('zhi.enginid,sum(list.money) as hougongzhifee,e.name as enginname')
                ->join('hou_gongzhi zhi','zhi.id=list.gongzhiid')
                ->join('engin e','e.id=zhi.enginid')
                ->where(['zhi.comid'=>$this->userinfo['comid'],'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
                ->where(['list.fuer'=>$item['name']])
                ->group('zhi.enginid')
                ->select()->toArray();
            foreach ($hougongzhi as $hougongzhi_VV){
                $enginList[$hougongzhi_VV['enginid']] = $hougongzhi_VV;
            }


            //销售方进项票累计
            $piaoshou = PiaoShouListModel::alias('list')
                ->field('shou.enginid,sum(list.money) as piaoshoufee,e.name as enginname')
                ->join('piao_shou shou','shou.id=list.shouid')
                ->join('engin e','e.id=shou.enginid')
                ->where(['shou.comid'=>$this->userinfo['comid'],'shou.deleted_user'=>0,'shou.isturn'=>1,'shou.status'=>1])
                ->where(['list.xiaoer'=>$item['name']])
                ->group('shou.enginid')
                ->select()->toArray();
            foreach ($piaoshou as $piaoshou_VV){
                if(isset($enginList[$piaoshou_VV['enginid']])){
                    $enginList[$piaoshou_VV['enginid']]['piaoshoufee'] = $piaoshou_VV['piaoshoufee'];
                }else{
                    $enginList[$piaoshou_VV['enginid']] = $piaoshou_VV;
                }
            }


            //销售方可签采购合同金额
            foreach ($enginList as &$en_VV){
                if(isset($en_VV['hougongzhifee']) && isset($en_VV['piaoshoufee'])){
                    $en_VV['keqiancai'] = $en_VV['hougongzhifee'] > $en_VV['piaoshoufee'] ? $en_VV['piaoshoufee'] : $en_VV['hougongzhifee'];
                }
            }


            //销售方已签采购合同金额
            $contractcai = ContractCaiModel::alias('cai')
                ->field('cai.enginid,e.name as enginname')
                ->join('engin e','e.id=cai.enginid')
                ->where(['cai.comid'=>$this->userinfo['comid'],'cai.deleted_user'=>0,'cai.isturn'=>1,'cai.status'=>1])
                ->where(['cai.gonger'=>$item['name']])
                ->group('cai.enginid')
                ->select()->toArray();
            foreach ($contractcai as $contractcai_VV){
                $contractcai_VV['yiqiancai'] = 0;
                $caiinfo = ContractCaiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                    ->where(['enginid'=>$contractcai_VV['enginid'],'gonger'=>$item['name']])->select()->toArray();
                foreach ($caiinfo as $caivvvvv){
                    $existJieMoney = ContractCaiJieModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                        ->where(['enginid'=>$contractcai_VV['enginid'],'caiid'=>$caivvvvv['id']])->sum('money');
                    if($existJieMoney){
                        $contractcai_VV['yiqiancai'] += $existJieMoney;
                    }else{
                        $contractcai_VV['yiqiancai'] += $caivvvvv['money'];
                    }
                }

                if(isset($enginList[$contractcai_VV['enginid']])){
                    $enginList[$contractcai_VV['enginid']]['yiqiancai'] = $contractcai_VV['yiqiancai'];
                }else{
                    $enginList[$contractcai_VV['enginid']] = $contractcai_VV;
                }
            }


            //销售方待签采购合同金额
            foreach ($enginList as $en22_KK => $en22_VV){
                if(!isset($en22_VV['keqiancai'])){
                    $en22_VV['keqiancai'] = 0;
                }
                if(!isset($en22_VV['yiqiancai'])){
                    $en22_VV['yiqiancai'] = 0;
                }
                $en22_VV['daiqiancai'] = round($en22_VV['keqiancai'] - $en22_VV['yiqiancai'], 2);
                $en22_VV['daiqiancai'] = $en22_VV['daiqiancai'] < 0 ? 0 : $en22_VV['daiqiancai'];
                if($en22_VV['daiqiancai']){
                    $enginList[$en22_KK]['daiqiancai'] = $en22_VV['daiqiancai'];
                }
            }


            //可抵扣进项票金额
            foreach ($enginList as &$en33_VV){
                if(isset($en33_VV['hougongzhifee']) && $en33_VV['hougongzhifee'] > 0
                    && isset($en33_VV['piaoshoufee']) && $en33_VV['piaoshoufee'] > 0
                    && isset($en33_VV['keqiancai']) && $en33_VV['keqiancai'] > 0) {
                    $en33_VV['kedijin'] = $en33_VV['hougongzhifee'] > $en33_VV['piaoshoufee'] ? $en33_VV['piaoshoufee'] : $en33_VV['hougongzhifee'];
                }
            }


            //已抵扣进项票价税合计
            $hougongshui = HouGongshuiListModel::alias('list')
                ->field('shui.enginid,sum(list.money) as yidijin,e.name as enginname')
                ->join('hou_gongshui shui','shui.id=list.gongshuiid')
                ->join('engin e','e.id=shui.enginid')
                ->where(['shui.comid'=>$this->userinfo['comid'],'shui.deleted_user'=>0,'shui.isturn'=>1,'shui.status'=>1])
                ->where(['list.xiaoer'=>$item['name']])
                ->group('shui.enginid')
                ->select()->toArray();
            foreach ($hougongshui as $hougongshui_VV){
                if(isset($enginList[$hougongshui_VV['enginid']])){
                    $enginList[$hougongshui_VV['enginid']]['yidijin'] = $hougongshui_VV['yidijin'];
                }else{
                    $enginList[$hougongshui_VV['enginid']] = $hougongshui_VV;
                }
            }

            //已抵扣退税
            $hougongshui22 = HouGongshuiListModel::alias('list')
                ->field('shui.enginid,sum(list.ratefee) as yidirate,e.name as enginname')
                ->join('hou_gongshui shui','shui.id=list.gongshuiid')
                ->join('engin e','e.id=shui.enginid')
                ->where(['shui.comid'=>$this->userinfo['comid'],'shui.deleted_user'=>0,'shui.isturn'=>1,'shui.status'=>1])
                ->where(['list.xiaoer'=>$item['name']])
                ->group('shui.enginid')
                ->select()->toArray();
            foreach ($hougongshui22 as $hougongshui22_VV){
                if(isset($enginList[$hougongshui22_VV['enginid']])){
                    $enginList[$hougongshui22_VV['enginid']]['yidirate'] = $hougongshui22_VV['yidirate'];
                }else{
                    $enginList[$hougongshui22_VV['enginid']] = $hougongshui22_VV;
                }
            }


            //剩余可抵扣进项票金额
            foreach ($enginList as $en4444_KK => $en4444_VV){
                if(!isset($en4444_VV['kedijin'])){
                    $en4444_VV['kedijin'] = 0;
                }
                if(!isset($en4444_VV['yidijin'])){
                    $en4444_VV['yidijin'] = 0;
                }
                $en4444_VV['shengdijin'] = round($en4444_VV['kedijin'] - $en4444_VV['yidijin'], 2);
                $en4444_VV['shengdijin'] = $en4444_VV['shengdijin'] < 0 ? 0 : $en4444_VV['shengdijin'];
                if($en4444_VV['shengdijin']){
                    $enginList[$en4444_KK]['shengdijin'] = $en4444_VV['shengdijin'];
                }
            }






            if($enginList){
                foreach ($enginList as $enginList_VV){
                    $enginList_VV['name'] = $item['name'];
                    $list[] = $enginList_VV;
                }
            }else{
                $list[] = ['name'=>$item['name']];
            }
        }

        $data['data'] = $list;
        return outputJson(2000,lang('code_2000'),$data);
    }


    public function list_engin_gong_tai(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];
        $where[] = ['e.isturn','=',1];
        $where[] = ['e.status','=',1];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['e.name','like', '%'.$param['name'].'%'];
        }

        $list = [];
        $data['data'] = EnginModel::alias('e')
            ->field('e.id,e.name')
            ->where($where)
            ->order('e.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){


                return $item;
            })->toArray();

        foreach ($data['data']['data'] as $item){
            $dealList = [];
            //累计支付销售方
            $hougongzhi = HouGongzhiListModel::alias('list')
                ->field('list.fuer as gonger,sum(list.money) as hougongzhifee')
                ->join('hou_gongzhi zhi','zhi.id=list.gongzhiid')
                ->join('engin e','e.id=zhi.enginid')
                ->where(['zhi.comid'=>$this->userinfo['comid'],'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
                ->where(['zhi.enginid'=>$item['id']])
                ->group('list.fuer')
                ->select()->toArray();
            foreach ($hougongzhi as $hougongzhi_VV){
                $isGong = DealcomModel::where(['name'=>$hougongzhi_VV['gonger']])->find();
                if(!$isGong || $isGong['deleted_user'] != 0 || $isGong['isturn'] != 1 || $isGong['status'] != 1){
                    continue;
                }

                $dealList[$hougongzhi_VV['gonger']] = $hougongzhi_VV;
            }


            //销售方进项票累计
            $piaoshou = PiaoShouListModel::alias('list')
                ->field('list.xiaoer as gonger,sum(list.money) as piaoshoufee,sum(list.ratefee) as piaoshouratefee')
                ->join('piao_shou shou','shou.id=list.shouid')
                ->join('engin e','e.id=shou.enginid')
                ->where(['shou.comid'=>$this->userinfo['comid'],'shou.deleted_user'=>0,'shou.isturn'=>1,'shou.status'=>1])
                ->where(['shou.enginid'=>$item['id']])
                ->group('list.xiaoer')
                ->select()->toArray();
            foreach ($piaoshou as $piaoshou_VV){
                $isGong = DealcomModel::where(['name'=>$piaoshou_VV['gonger']])->find();
                if(!$isGong || $isGong['deleted_user'] != 0 || $isGong['isturn'] != 1 || $isGong['status'] != 1){
                    continue;
                }

                if(isset($dealList[$piaoshou_VV['gonger']])){
                    $dealList[$piaoshou_VV['gonger']]['piaoshoufee'] = $piaoshou_VV['piaoshoufee'];
                    $dealList[$piaoshou_VV['gonger']]['piaoshouratefee'] = $piaoshou_VV['piaoshouratefee'];
                }else{
                    $dealList[$piaoshou_VV['gonger']] = $piaoshou_VV;
                }
            }


            //销售方可签采购合同金额
            foreach ($dealList as &$en_VV){
                if(isset($en_VV['hougongzhifee']) && isset($en_VV['piaoshoufee'])){
                    $en_VV['keqiancai'] = $en_VV['hougongzhifee'] > $en_VV['piaoshoufee'] ? $en_VV['piaoshoufee'] : $en_VV['hougongzhifee'];
                }
            }


            //销售方已签采购合同金额
            $contractcai = ContractCaiModel::alias('cai')
                ->field('cai.gonger')
                ->join('engin e','e.id=cai.enginid')
                ->where(['cai.comid'=>$this->userinfo['comid'],'cai.deleted_user'=>0,'cai.isturn'=>1,'cai.status'=>1])
                ->where(['cai.enginid'=>$item['id']])
                ->group('cai.gonger')
                ->select()->toArray();
            foreach ($contractcai as $contractcai_VV){
                $isGong = DealcomModel::where(['name'=>$contractcai_VV['gonger']])->find();
                if(!$isGong || $isGong['deleted_user'] != 0 || $isGong['isturn'] != 1 || $isGong['status'] != 1){
                    continue;
                }


                $contractcai_VV['yiqiancai'] = 0;
                $caiinfo = ContractCaiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                    ->where(['enginid'=>$item['id'],'gonger'=>$contractcai_VV['gonger']])->select()->toArray();
                foreach ($caiinfo as $caivvvvv){
                    $existJieMoney = ContractCaiJieModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                        ->where(['enginid'=>$item['id'],'caiid'=>$caivvvvv['id']])->sum('money');
                    if($existJieMoney){
                        $contractcai_VV['yiqiancai'] += $existJieMoney;
                    }else{
                        $contractcai_VV['yiqiancai'] += $caivvvvv['money'];
                    }
                }
                $contractcai_VV['shencai'] = ContractCaiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>0])
                    ->where(['enginid'=>$item['id'],'gonger'=>$contractcai_VV['gonger']])->sum('money');




                if(isset($dealList[$contractcai_VV['gonger']])){
                    $dealList[$contractcai_VV['gonger']]['yiqiancai'] = $contractcai_VV['yiqiancai'];
                    $dealList[$contractcai_VV['gonger']]['shencai'] = $contractcai_VV['shencai'];
                }else{
                    $dealList[$contractcai_VV['gonger']] = $contractcai_VV;
                }
            }


            //销售方待签采购合同金额
            foreach ($dealList as $en22_KK => $en22_VV){
                if(!isset($en22_VV['keqiancai'])){
                    $en22_VV['keqiancai'] = 0;
                }
                if(!isset($en22_VV['yiqiancai'])){
                    $en22_VV['yiqiancai'] = 0;
                }
                $en22_VV['daiqiancai'] = round($en22_VV['keqiancai'] - $en22_VV['yiqiancai'], 2);
                $en22_VV['daiqiancai'] = $en22_VV['daiqiancai'] < 0 ? 0 : $en22_VV['daiqiancai'];
                if($en22_VV['daiqiancai']){
                    $dealList[$en22_KK]['daiqiancai'] = $en22_VV['daiqiancai'];
                }
            }


            //可抵扣进项票金额
            foreach ($dealList as &$en33_VV){
                if(isset($en33_VV['hougongzhifee']) && $en33_VV['hougongzhifee'] > 0
                    && isset($en33_VV['piaoshoufee']) && $en33_VV['piaoshoufee'] > 0
                    && isset($en33_VV['yiqiancai']) && $en33_VV['yiqiancai'] > 0) {
                    $en33_VV['kedijin'] = $en33_VV['hougongzhifee'] > $en33_VV['piaoshoufee'] ? $en33_VV['piaoshoufee'] : $en33_VV['hougongzhifee'];
                }
            }


            //已抵扣进项票价税合计
            $hougongshui = HouGongshuiListModel::alias('list')
                ->field('list.xiaoer as gonger,sum(list.money) as yidijin')
                ->join('hou_gongshui shui','shui.id=list.gongshuiid')
                ->join('engin e','e.id=shui.enginid')
                ->where(['shui.comid'=>$this->userinfo['comid'],'shui.deleted_user'=>0,'shui.isturn'=>1,'shui.status'=>1])
                ->where(['shui.enginid'=>$item['id']])
                ->group('list.xiaoer')
                ->select()->toArray();
            foreach ($hougongshui as $hougongshui_VV){
                $isGong = DealcomModel::where(['name'=>$hougongshui_VV['gonger']])->find();
                if(!$isGong || $isGong['deleted_user'] != 0 || $isGong['isturn'] != 1 || $isGong['status'] != 1){
                    continue;
                }

                if(isset($dealList[$hougongshui_VV['gonger']])){
                    $dealList[$hougongshui_VV['gonger']]['yidijin'] = $hougongshui_VV['yidijin'];
                }else{
                    $dealList[$hougongshui_VV['gonger']] = $hougongshui_VV;
                }
            }

            //已抵扣退税
            $hougongshui22 = HouGongshuiListModel::alias('list')
                ->field('list.xiaoer as gonger,sum(list.ratefee) as yidirate')
                ->join('hou_gongshui shui','shui.id=list.gongshuiid')
                ->join('engin e','e.id=shui.enginid')
                ->where(['shui.comid'=>$this->userinfo['comid'],'shui.deleted_user'=>0,'shui.isturn'=>1,'shui.status'=>1])
                ->where(['shui.enginid'=>$item['id']])
                ->group('list.xiaoer')
                ->select()->toArray();
            foreach ($hougongshui22 as $hougongshui22_VV){
                $isGong = DealcomModel::where(['name'=>$hougongshui22_VV['gonger']])->find();
                if(!$isGong || $isGong['deleted_user'] != 0 || $isGong['isturn'] != 1 || $isGong['status'] != 1){
                    continue;
                }

                if(isset($dealList[$hougongshui22_VV['gonger']])){
                    $dealList[$hougongshui22_VV['gonger']]['yidirate'] = $hougongshui22_VV['yidirate'];
                }else{
                    $dealList[$hougongshui22_VV['gonger']] = $hougongshui22_VV;
                }
            }


            //剩余可抵扣进项票金额
            foreach ($dealList as $en4444_KK => $en4444_VV){
                if(!isset($en4444_VV['kedijin'])){
                    $en4444_VV['kedijin'] = 0;
                }
                if(!isset($en4444_VV['yidijin'])){
                    $en4444_VV['yidijin'] = 0;
                }
                $en4444_VV['shengdijin'] = round($en4444_VV['kedijin'] - $en4444_VV['yidijin'], 2);
                $en4444_VV['shengdijin'] = $en4444_VV['shengdijin'] < 0 ? 0 : $en4444_VV['shengdijin'];
                if($en4444_VV['shengdijin']){
                    $dealList[$en4444_KK]['shengdijin'] = $en4444_VV['shengdijin'];
                }
            }






            if($dealList){
                foreach ($dealList as $dealList_VV){
                    $dealList_VV['enginid'] = $item['id'];
                    $dealList_VV['enginname'] = $item['name'];
                    $list[] = $dealList_VV;
                }
            }else{
                $list[] = ['enginname'=>$item['name'],'enginid'=>$item['id']];
            }
        }

        foreach ($list as &$mmm){
            if(isset($mmm['gonger'])){
                $mmm['shencai'] = ContractCaiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>0])
                    ->where(['enginid'=>$mmm['enginid'],'gonger'=>$mmm['gonger']])->sum('money');
            }
        }



        $data['data']['data'] = $list;
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_gong_tai222(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];
        $where[] = ['e.isturn','=',1];
        $where[] = ['e.status','=',1];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['e.name','like', '%'.$param['name'].'%'];
        }

        $list = [];
        $engininfo = EnginModel::alias('e')
            ->field('e.id,e.name')
            ->where($where)
            ->order('e.id DESC')
            ->select()->toArray();
        foreach ($engininfo as $item){
            $dealList = [];

            //累计支付销售方
            $hougongzhi = HouGongzhiListModel::alias('list')
                ->field('list.fuer as gonger,sum(list.money) as hougongzhifee')
                ->join('hou_gongzhi zhi','zhi.id=list.gongzhiid')
                ->join('engin e','e.id=zhi.enginid')
                ->where(['zhi.comid'=>$this->userinfo['comid'],'zhi.deleted_user'=>0,'zhi.isturn'=>1,'zhi.status'=>1])
                ->where(['zhi.enginid'=>$item['id']])
                ->group('list.fuer')
                ->select()->toArray();
            foreach ($hougongzhi as $hougongzhi_VV){
                $isGong = DealcomModel::where(['name'=>$hougongzhi_VV['gonger']])->find();
                if(!$isGong || $isGong['deleted_user'] != 0 || $isGong['isturn'] != 1 || $isGong['status'] != 1 || $isGong['type'] != 3){
                    continue;
                }

                $dealList[$hougongzhi_VV['gonger']] = $hougongzhi_VV;
            }


            //销售方进项票累计
            $piaoshou = PiaoShouListModel::alias('list')
                ->field('list.xiaoer as gonger,sum(list.money) as piaoshoufee')
                ->join('piao_shou shou','shou.id=list.shouid')
                ->join('engin e','e.id=shou.enginid')
                ->where(['shou.comid'=>$this->userinfo['comid'],'shou.deleted_user'=>0,'shou.isturn'=>1,'shou.status'=>1])
                ->where(['shou.enginid'=>$item['id']])
                ->group('list.xiaoer')
                ->select()->toArray();
            foreach ($piaoshou as $piaoshou_VV){
                $isGong = DealcomModel::where(['name'=>$piaoshou_VV['gonger']])->find();
                if(!$isGong || $isGong['deleted_user'] != 0 || $isGong['isturn'] != 1 || $isGong['status'] != 1 || $isGong['type'] != 3){
                    continue;
                }

                if(isset($dealList[$piaoshou_VV['gonger']])){
                    $dealList[$piaoshou_VV['gonger']]['piaoshoufee'] = $piaoshou_VV['piaoshoufee'];
                }else{
                    $dealList[$piaoshou_VV['gonger']] = $piaoshou_VV;
                }
            }


            //销售方可签采购合同金额
            foreach ($dealList as &$en_VV){
                if(isset($en_VV['hougongzhifee']) && isset($en_VV['piaoshoufee'])){
                    $en_VV['keqiancai'] = $en_VV['hougongzhifee'] > $en_VV['piaoshoufee'] ? $en_VV['piaoshoufee'] : $en_VV['hougongzhifee'];
                }
            }


            //销售方已签采购合同金额
            $contractcai = ContractCaiModel::alias('cai')
                ->field('cai.gonger')
                ->join('engin e','e.id=cai.enginid')
                ->where(['cai.comid'=>$this->userinfo['comid'],'cai.deleted_user'=>0,'cai.isturn'=>1,'cai.status'=>1])
                ->where(['cai.enginid'=>$item['id']])
                ->group('cai.gonger')
                ->select()->toArray();
            foreach ($contractcai as $contractcai_VV){
                $isGong = DealcomModel::where(['name'=>$contractcai_VV['gonger']])->find();
                if(!$isGong || $isGong['deleted_user'] != 0 || $isGong['isturn'] != 1 || $isGong['status'] != 1 || $isGong['type'] != 3){
                    continue;
                }


                $contractcai_VV['yiqiancai'] = 0;
                $caiinfo = ContractCaiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                    ->where(['enginid'=>$item['id'],'gonger'=>$contractcai_VV['gonger']])->select()->toArray();
                foreach ($caiinfo as $caivvvvv){
                    $existJieMoney = ContractCaiJieModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                        ->where(['enginid'=>$item['id'],'caiid'=>$caivvvvv['id']])->sum('money');
                    if($existJieMoney){
                        $contractcai_VV['yiqiancai'] += $existJieMoney;
                    }else{
                        $contractcai_VV['yiqiancai'] += $caivvvvv['money'];
                    }
                }

                if(isset($dealList[$contractcai_VV['gonger']])){
                    $dealList[$contractcai_VV['gonger']]['yiqiancai'] = $contractcai_VV['yiqiancai'];
                }else{
                    $dealList[$contractcai_VV['gonger']] = $contractcai_VV;
                }
            }


            //销售方待签采购合同金额
            foreach ($dealList as $en22_KK => $en22_VV){
                if(!isset($en22_VV['keqiancai'])){
                    $en22_VV['keqiancai'] = 0;
                }
                if(!isset($en22_VV['yiqiancai'])){
                    $en22_VV['yiqiancai'] = 0;
                }
                $en22_VV['daiqiancai'] = round($en22_VV['keqiancai'] - $en22_VV['yiqiancai'], 2);
                $en22_VV['daiqiancai'] = $en22_VV['daiqiancai'] < 0 ? 0 : $en22_VV['daiqiancai'];
                if($en22_VV['daiqiancai']){
                    $dealList[$en22_KK]['daiqiancai'] = $en22_VV['daiqiancai'];
                }
            }


            //可抵扣进项票金额
            foreach ($dealList as &$en33_VV){
                if(isset($en33_VV['hougongzhifee']) && $en33_VV['hougongzhifee'] > 0
                    && isset($en33_VV['piaoshoufee']) && $en33_VV['piaoshoufee'] > 0
                    && isset($en33_VV['yiqiancai']) && $en33_VV['yiqiancai'] > 0) {
                    $en33_VV['kedijin'] = $en33_VV['hougongzhifee'] > $en33_VV['piaoshoufee'] ? $en33_VV['piaoshoufee'] : $en33_VV['hougongzhifee'];
                }
            }


            //已抵扣进项票价税合计
            $hougongshui = HouGongshuiListModel::alias('list')
                ->field('list.xiaoer as gonger,sum(list.money) as yidijin')
                ->join('hou_gongshui shui','shui.id=list.gongshuiid')
                ->join('engin e','e.id=shui.enginid')
                ->where(['shui.comid'=>$this->userinfo['comid'],'shui.deleted_user'=>0,'shui.isturn'=>1,'shui.status'=>1])
                ->where(['shui.enginid'=>$item['id']])
                ->group('list.xiaoer')
                ->select()->toArray();
            foreach ($hougongshui as $hougongshui_VV){
                $isGong = DealcomModel::where(['name'=>$hougongshui_VV['gonger']])->find();
                if(!$isGong || $isGong['deleted_user'] != 0 || $isGong['isturn'] != 1 || $isGong['status'] != 1 || $isGong['type'] != 3){
                    continue;
                }

                if(isset($dealList[$hougongshui_VV['gonger']])){
                    $dealList[$hougongshui_VV['gonger']]['yidijin'] = $hougongshui_VV['yidijin'];
                }else{
                    $dealList[$hougongshui_VV['gonger']] = $hougongshui_VV;
                }
            }

            //已抵扣退税
            $hougongshui22 = HouGongshuiListModel::alias('list')
                ->field('list.xiaoer as gonger,sum(list.ratefee) as yidirate')
                ->join('hou_gongshui shui','shui.id=list.gongshuiid')
                ->join('engin e','e.id=shui.enginid')
                ->where(['shui.comid'=>$this->userinfo['comid'],'shui.deleted_user'=>0,'shui.isturn'=>1,'shui.status'=>1])
                ->where(['shui.enginid'=>$item['id']])
                ->group('list.xiaoer')
                ->select()->toArray();
            foreach ($hougongshui22 as $hougongshui22_VV){
                $isGong = DealcomModel::where(['name'=>$hougongshui22_VV['gonger']])->find();
                if(!$isGong || $isGong['deleted_user'] != 0 || $isGong['isturn'] != 1 || $isGong['status'] != 1 || $isGong['type'] != 3){
                    continue;
                }

                if(isset($dealList[$hougongshui22_VV['gonger']])){
                    $dealList[$hougongshui22_VV['gonger']]['yidirate'] = $hougongshui22_VV['yidirate'];
                }else{
                    $dealList[$hougongshui22_VV['gonger']] = $hougongshui22_VV;
                }
            }


            //剩余可抵扣进项票金额
            foreach ($dealList as $en4444_KK => $en4444_VV){
                if(!isset($en4444_VV['kedijin'])){
                    $en4444_VV['kedijin'] = 0;
                }
                if(!isset($en4444_VV['yidijin'])){
                    $en4444_VV['yidijin'] = 0;
                }
                $en4444_VV['shengdijin'] = round($en4444_VV['kedijin'] - $en4444_VV['yidijin'], 2);
                $en4444_VV['shengdijin'] = $en4444_VV['shengdijin'] < 0 ? 0 : $en4444_VV['shengdijin'];
                if($en4444_VV['shengdijin']){
                    $dealList[$en4444_KK]['shengdijin'] = $en4444_VV['shengdijin'];
                }
            }






            if($dealList){
                foreach ($dealList as $dealList_VV){
                    $dealList_VV['enginid'] = $item['id'];
                    $dealList_VV['enginname'] = $item['name'];
                    $list[] = $dealList_VV;
                }
            }else{
                $list[] = ['enginname'=>$item['name'],'enginid'=>$item['id']];
            }
        }

        $data['data'] = $list;
        return outputJson(2000,lang('code_2000'),$data);
    }




    public function list_chu_deal_tai(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['deal.deleted_user','=', 0];
        $where[] = ['deal.comid','=',$this->userinfo['comid']];
        $where[] = ['deal.isturn','=',1];
        $where[] = ['deal.status','=',1];
        $where[] = ['deal.type','=',6];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['deal.name','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['deal.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['lianer']) && !empty($param['lianer'])){
            $where[] = ['deal.lianer','like', '%'.$param['lianer'].'%'];
        }

        $data['data'] = DealcomModel::alias('deal')
            ->field('deal.*')
            ->where($where)
            ->order('deal.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['conmoney'] = ContractChuModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                    ->where(['gonger'=>$item['name']])->sum('money');

//                $item['jiemoney'] = ContractChuJieModel::alias('jie')
//                    ->join('contract_chu chu','chu.id=jie.chuid')
//                    ->where(['jie.comid'=>$this->userinfo['comid'],'jie.deleted_user'=>0,'jie.isturn'=>1,'jie.status'=>1])
//                    ->where(['chu.comid'=>$this->userinfo['comid'],'chu.deleted_user'=>0,'chu.isturn'=>1,'chu.status'=>1])
//                    ->where(['chu.gonger'=>$item['name']])
//                    ->sum('jie.money');

                $item['piaofee'] = PiaoChuListModel::alias('list')
                    ->join('piao_chu chu','chu.id=list.piaochuid')
                    ->where(['chu.comid'=>$this->userinfo['comid'],'chu.deleted_user'=>0,'chu.isturn'=>1,'chu.status'=>1])
                    ->where(['list.xiaoer'=>$item['name']])
                    ->sum('list.money');

                $item['chujinfee'] = HouChujinListModel::alias('list')
                    ->join('hou_chujin chu','chu.id=list.chujinid')
                    ->where(['chu.comid'=>$this->userinfo['comid'],'chu.deleted_user'=>0,'chu.isturn'=>1,'chu.status'=>1])
                    ->where(['list.fuer'=>$item['name']])
                    ->sum('list.money');

                $item['chushuifee'] = HouChushuiListModel::alias('list')
                    ->join('hou_chushui chu','chu.id=list.chushuiid')
                    ->where(['chu.comid'=>$this->userinfo['comid'],'chu.deleted_user'=>0,'chu.isturn'=>1,'chu.status'=>1])
                    ->where(['list.fuer'=>$item['name']])
                    ->sum('list.money');

                $item['chushuiduigongfee'] = HouChushuiListModel::alias('list')
                    ->join('hou_chushui chu','chu.id=list.chushuiid')
                    ->where(['chu.comid'=>$this->userinfo['comid'],'chu.deleted_user'=>0,'chu.isturn'=>1,'chu.status'=>1])
                    ->where(['list.fuer'=>$item['name'],'list.fulei'=>'对公'])
                    ->sum('list.money');

                $item['leizhifee'] = round($item['chujinfee'] + $item['chushuiduigongfee'], 2);


                $item['daiqianfee'] = round($item['piaofee'] - $item['conmoney'], 2);

                return $item;
            })->toArray();


        return outputJson(2000,lang('code_2000'),$data);
    }




    public function list_engin_dao(Request $request){
        $param = $request->post();
        get_page($param);
        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];
        $where[] = ['e.isturn','=',1];
        $where[] = ['e.status','=',1];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name|e.number','like', '%'.$param['keyword'].'%'];
        }

        $whereMiss = [];
        if($this->userinfo['token_roletype'] == 1){
            //全部权限
        }
        if($this->userinfo['token_roletype'] == 2){
            $enginArr = (new EnginService())->get_user_engin();
            $whereMiss[] = ['e.id','in',$enginArr];
        }
        if($this->userinfo['token_roletype'] == 3){
            $lianerarr = DealcomModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                ->where('id','in',$this->userinfo['lianer'])->column('name');
            $enginArr = EnginModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'status'=>1,'isturn'=>1,'business'=>2])
                ->where('lian_unit','in',$lianerarr)->column('id');
            $whereMiss[] = ['e.id','in',$enginArr];
        }
        if($this->userinfo['token_roletype'] == 4){
            $where[] = ['e.id','<',0];
        }
        if($this->userinfo['token_roletype'] == 5){
            $userChanid = (new UserService())->get_user_chanid();
            $whereMiss[] = ['e.chanid','=',$userChanid];
        }

        $data = EnginModel::alias('e')
            ->field('e.id,e.name as title')
            ->where($where)
            ->where($whereMiss)
            ->order('e.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                return $item;
            })->toArray();
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_enginmy(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];
        $where[] = ['e.isturn','=',1];
        $where[] = ['e.status','=',1];

        $param_business = isset($param['business']) ? $param['business'] : 0;
        if($param_business > 0){
            $where[] = ['e.business','=',$param_business];
        }
        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name|e.number|e.jian_unit|e.areas','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['lian_unit']) && !empty($param['lian_unit'])){
            $where[] = ['e.lian_unit','like', '%'.$param['lian_unit'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['e.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['e.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['engintype']) && !empty($param['engintype'])){
            $where[] = ['e.engintype','=', $param['engintype']];
        }
        if(isset($param['jian_unit']) && !empty($param['jian_unit'])){
            $where[] = ['e.jian_unit','like', '%'.$param['jian_unit'].'%'];
        }
        if(isset($param['areas']) && !empty($param['areas'])){
            $where[] = ['e.areas','like', '%'.$param['areas'].'%'];
        }


        if(isset($param['startdt']) && !empty($param['startdt'])){
            $where[] = ['e.startdt','between', explode(' - ', $param['startdt'])];
        }
        if(isset($param['enddt']) && !empty($param['enddt'])){
            $where[] = ['e.enddt','between', explode(' - ', $param['enddt'])];
        }
        if(isset($param['state']) && $param['state'] != ''){
            $where[] = ['e.state','=', $param['state']];
        }
        if(isset($param['zhaotype']) && !empty($param['zhaotype'])){
            $where[] = ['e.zhaotype','=', $param['zhaotype']];
        }
        if(isset($param['actualdt']) && !empty($param['actualdt'])){
            $where[] = ['e.actualdt','between', explode(' - ', $param['actualdt'])];
        }
        if(isset($param['filishdt']) && !empty($param['filishdt'])){
            $where[] = ['e.filishdt','between', explode(' - ', $param['filishdt'])];
        }
        if(isset($param['chanid']) && !empty($param['chanid'])){
            $where[] = ['e.chanid','=', $param['chanid']];
        }



        $data['chanid'] = (new UserService())->get_chaninfo_all();;
        $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';


        $state = (new EnginService())->get_engin_state();
        $data['state'] = $state;
        $data['is_state'] = isset($param['state']) ? $param['state'] : '';

        $data['engintype'] = (new OptService())->get_base_info('engin_engintype');
        $data['is_engintype'] = isset($param['engintype']) ? $param['engintype'] : '';

        $data['zhaotype'] = (new OptService())->get_base_info('bid_bidding_type');
        $data['is_zhaotype'] = isset($param['zhaotype']) ? $param['zhaotype'] : '';



        $fisStr = "find_in_set(".$this->userinfo['id'].",e.man_zhuan)";
        $fisStr .= " or find_in_set(".$this->userinfo['id'].",e.man_zi)";
        $fisStr .= " or find_in_set(".$this->userinfo['id'].",e.man_cheng)";
        $fisStr .= " or find_in_set(".$this->userinfo['id'].",e.man_zhian)";
        $fisStr .= " or e.man_xiang=".$this->userinfo['id'];
        $whereFis = Db::raw($fisStr);


        $data['data'] = EnginModel::alias('e')
            ->field('e.*')
            ->where($where)
            ->where($whereFis)
            ->order('e.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['business_name'] = $item['business'] == 1 ? '自营' : '联营';
                $item['state_name'] = (new EnginService())->get_engin_state_name_tag($item['id'], $item['state']);
                $item['state_name_mob'] = (new EnginService())->get_engin_state_name($item['id'], $item['state']);
                $item['isting'] = $item['state'] == 3 ? true : false;

                $item['engintype'] = (new OptService())->get_base_showname('engin_engintype', $item['engintype']);
                $item['zhaotype'] = (new OptService())->get_base_showname('bid_bidding_type', $item['zhaotype']);
                return $item;
            })->toArray();

        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_engin(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入工程名称');
            }
            if((new EnginService())->check_engin_name($param['name'])){
                return outputJson(4000, '工程名称已存在');
            }
            if($param['business'] == 2){
                if(empty($param['lian_unit'])){
                    return outputJson(4000, '请选择联营方');
                }
            }
            if(empty($param['chanid'])){
                return outputJson(4000, '请选择所属单位');
            }
            if($param['state'] == ''){
                return outputJson(4000, '请选择项目状态');
            }
            if($param['state'] == 0){
                $param['actualdt'] = '';
                $param['filishdt'] = '';
            }
            if($param['state'] == 3){
                $param['filishdt'] = '';
            }

            if($param['business'] == 2){
                if(empty($param['lian_unit'])){
                    return outputJson(4000, '请选择联营方');
                }
            }


            $param['comid'] = $this->userinfo['comid'];
            $param['isturn'] = 1;
            $param['status'] = 1;
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            $param['deptid'] = $this->userinfo['deptid'];

            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);

            Db::startTrans();
            try {
                $id = EnginModel::insertGetId($param);
                (new EnginRelevan())->vate_engin_add_mingxi($id);
                (new OptService())->relation_file($files,'engin',$id);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'engin', $id);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'engin', $id, '项目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['engintype'] = (new OptService())->get_base_info('engin_engintype');
            $data['zhaotype'] = (new OptService())->get_base_info('bid_bidding_type');
            $data['areas'] = (new OptService())->get_city_cader();
            $data['state'] = (new EnginService())->get_engin_state();
            $data['files'] = (new OptService())->get_file('engin');
            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function edit_engin(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入工程名称');
            }
            if((new EnginService())->check_engin_name($param['name'], $param['id'])){
                return outputJson(4000, '工程名称已存在');
            }
            if(empty($param['jiaer'])){
                return outputJson(4000, '请输入甲方名称');
            }
            if(empty($param['gui_unit'])){
                return outputJson(4000, '请选择业务归属');
            }
            if(empty($param['lanshi'])){
                return outputJson(4000, '请选择承揽方式');
            }
            if($param['lantake'] == 2){

                if(empty($param['kailei'])){
                    return outputJson(4000, '请选择工程性质');
                }
                if(empty($param['zhaotype'])){
                    return outputJson(4000, '请选择招标方式');
                }
                if(empty($param['win_unit'])){
                    return outputJson(4000, '请选择中标单位');
                }
            }
            if($param['state'] == ''){
                return outputJson(4000, '请选择工程状态');
            }


            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');

            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);


            Db::startTrans();
            try {
                EnginModel::update($param);

                if($param['state'] == 5 || $param['state'] == 7){
                    (new CertRelevan())->set_cert_use_shi_quan($param['id']);
                }
                (new CertRelevan())->set_cert_statueuse_engin($param['id']);

                (new OptService())->relation_file($files,'engin',$param['id']);
                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'engin', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'engin', $param['id'], '工程承揽');

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }

            $data['data']['win_unit_info'] = (new UserService())->get_users_part_arr($data['data']['win_unit'], 'dept');
            $data['data']['gui_unit_info'] = (new UserService())->get_users_part_arr($data['data']['gui_unit'], 'dept');

            $data['lantake'] = (new EnginService())->get_engin_lantake();
            $data['state'] = (new EnginService())->get_engin_state();
            $data['lanshi'] = (new OptService())->get_base_info('bid_lanshi');
            $data['kailei'] = (new OptService())->get_base_info('bid_kailei');
            $data['zhaotype'] = (new OptService())->get_base_info('bid_zhaotype');
            $data['gonghelei'] = (new OptService())->get_base_info('engin_gonghelei');
            $data['areas'] = (new OptService())->get_city_cader();


            $data['files'] = (new OptService())->get_file('engin', $data['data']['id']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function kaijun_engin(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if($param['state'] == ''){
                return outputJson(4000, '请选择变更状态');
            }
            if($param['state'] == 0){
                $param['actualdt'] = '';
                $param['filishdt'] = '';
            }
            if($param['state'] == 3){
                $param['filishdt'] = '';
            }

            unset($param['token']);

            $statusname = '';
            if($param['state'] == 0){
                $statusname = '未开工';
            }
            if($param['state'] == 3){
                $statusname = '在建';
            }
            if($param['state'] == 6){
                $statusname = '合同竣工(人员释放)';
            }

            $oldinfo = EnginModel::where(['id'=>$param['id']])->find();

            Db::startTrans();
            try {
                EnginModel::update($param);

                if($oldinfo['state'] == 0 || $oldinfo['state'] == 3){
                    if($param['state'] == 6){
                        (new CertRelevan())->set_cert_statueuse_engin($param['id']);
                    }
                }else{
                    if($param['state'] == 0 || $param['state'] == 3){
                        (new CertRelevan())->set_cert_statueuse_engin($param['id']);
                    }
                }

                (new OptService())->add_flow_log('开竣工', 'engin', $param['id'],$statusname);
                (new OptService())->add_log_list('开竣工', 'engin', $param['id'], '项目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }

            $data['data']['state_name'] = (new EnginService())->get_engin_state_name($data['data']['id'], $data['data']['state']);
            $data['state'] = (new EnginService())->get_engin_state();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function ting_engin(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $engin = EnginModel::where(['id'=>$param['id']])->find();
            if(!$engin){
                return outputJson(4000,lang('code_4000'));
            }
            if($engin['state'] != 3){
                return outputJson(4000, lang('code_4000'));
            }

            if(empty($param['dt'])){
                return outputJson(4000, '请选择日期');
            }


            $param['enginid'] = $engin['id'];
            $param['created_user'] = $this->userinfo['id'];
            $param['created_at'] = date('Y-m-d H:i:s');


            unset($param['id']);
            unset($param['token']);

            Db::startTrans();
            try {
                $id = EnginTingModel::insertGetId($param);
                (new OptService())->add_flow_log('停复工', 'engin', $param['enginid'], $param['name'], $param['explain']);
                (new OptService())->add_log_list('停复工', 'engin', $param['enginid'], '项目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }

            if($data['data']['state'] != 3){
                return outputJson(4000, lang('code_4000'));
            }

            $data['data']['tingname'] = '停工';
            $tingNew = EnginTingModel::where(['enginid'=>$data['data']['id']])->order('id DESC')->find();
            if($tingNew){
                if($tingNew['name'] == '停工'){
                    $data['data']['tingname'] = '复工';
                }
            }
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function beian_engin(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $list = array_filter($param['list']);
            unset($param['list']);

            Db::startTrans();
            try {
                if (count($list) > 0) {
                    foreach ($list as $item) {
                        CertUseListModel::update($item);
                    }
                }

                (new OptService())->add_flow_log('编辑备案人员', 'engin', $param['id']);
                (new OptService())->add_log_list('编辑备案人员', 'engin', $param['id'], '项目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }

            $list = CertUseListModel::alias('list')->field('list.*')
                ->leftJoin('cert_use use','use.id = list.mid')
                // ->where(['use.enginid'=>$id,'use.deleted_user'=>0,'use.type'=>2,'list.pid'=>0,'list.isdel'=>0])
                ->where(['use.enginid'=>$id,'use.deleted_user'=>0,'use.type'=>2])
                ->select()->toArray();
            foreach ($list as &$v){
                $cert_data = CertModel::where('id',$v['cert_id'])->find();
                $v['cert_name'] = $cert_data['name'];
                $v['cert_number'] = $cert_data['number'];
                $v['cert_major'] = str_replace('[]', ',', $cert_data['major']);
                $v['person_name'] = CertPersonModel::where('id',$cert_data['personid'])->value('name');
                $v['use'] = '';
                $v['com_name'] = DeptModel::get_name_by_pk($cert_data['chanid']);
                $v['issuo_name'] = $v['issuo'] == 1 ? '是' : '否';
            }
            $data['list'] = $list;
            $data['issuo'] = CertUseModel::get_issuo();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function beian_engin1(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $list = array_filter($param['list']);
            unset($param['list']);

            Db::startTrans();
            try {
                EnginBeianModel::where(['enginid' => $param['id']])->delete();
                if (count($list) > 0) {
                    foreach ($list as $item) {
                        $item['enginid'] = $param['id'];
                        EnginBeianModel::insert($item);
                    }
                }
                (new OptService())->add_flow_log('编辑备案人员', 'engin', $param['id']);
                (new OptService())->add_log_list('编辑备案人员', 'engin', $param['id'], '项目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }

            $list = EnginBeianModel::where(['enginid'=>$data['data']['id']])->select()->toArray();
            foreach ($list as &$item){
                $item['cert_name'] = '';
                $item['cert_number'] = '';
                $item['cert_major'] = '';
                $item['person_name'] = '';
                $cert = CertModel::where(['id'=>$item['certid']])->find();
                if($cert){
                    $person = CertPersonModel::where(['id'=>$cert['personid']])->find();
                    $item['cert_name'] = $cert['name'];
                    $item['cert_number'] = $cert['number'];
                    $item['cert_major'] = str_replace('[]',',',$cert['major']);
                    $item['person_name'] = $person['name'];
                }
            }

            $data['list'] = $list;

            $data['list'] = $list;
            $data['beiangang'] = (new OptService())->get_base_info('engin_beiangang');
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function xian_engin(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $list = array_filter($param['list']);
            unset($param['list']);

            Db::startTrans();
            try {
                EnginXianModel::where(['enginid' => $param['id']])->delete();
                if (count($list) > 0) {
                    foreach ($list as $item) {
                        $item['enginid'] = $param['id'];
                        EnginXianModel::insert($item);
                    }
                }
                (new OptService())->add_flow_log('编辑现场人员', 'engin', $param['id']);
                (new OptService())->add_log_list('编辑现场人员', 'engin', $param['id'], '项目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }

            $list = EnginXianModel::where(['enginid'=>$data['data']['id']])->select()->toArray();
            foreach ($list as $k=>&$v){
                    $v['beiangang_name'] = (new OptService())->get_base_showname('engin_beiangang', $v['beiangang']);
            }
            $data['list'] = $list;
            $data['beiangang'] = (new OptService())->get_base_info('engin_beiangang');
            $data['beiangangOrder'] = (new OptService())->get_base_order('engin_beiangang');
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function manage_engin(Request $request){
        if($request->isPost()){
            $param = $request->post();

            unset($param['token']);

            Db::startTrans();
            try {
                EnginModel::update($param);
                (new OptService())->add_flow_log('编辑项目管理组', 'engin', $param['id']);
                (new OptService())->add_log_list('编辑项目管理组', 'engin', $param['id'], '项目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }
            $data['data']['business_name'] = $data['data']['business'] == 1 ? '自营' : '联营';
            $data['data']['man_xiang_info'] = (new UserService())->get_users_part_arr($data['data']['man_xiang'], 'user');
            $data['data']['man_zhuan_info'] = (new UserService())->get_users_part_arr($data['data']['man_zhuan'], 'user');
            $data['data']['man_zi_info'] = (new UserService())->get_users_part_arr($data['data']['man_zi'], 'user');
            $data['data']['man_cheng_info'] = (new UserService())->get_users_part_arr($data['data']['man_cheng'], 'user');
            $data['data']['man_zhian_info'] = (new UserService())->get_users_part_arr($data['data']['man_zhian'], 'user');

            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function duty_engin(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $list = array_filter($param['list']);
            unset($param['list']);

            Db::startTrans();
            try {
                EnginDutyModel::where(['enginid' => $param['id']])->delete();
                if (count($list) > 0) {
                    foreach ($list as $item) {
                        $item['enginid'] = $param['id'];
                        EnginDutyModel::insert($item);
                    }
                }
                (new OptService())->add_flow_log('编辑责任主体', 'engin', $param['id']);
                (new OptService())->add_log_list('编辑责任主体', 'engin', $param['id'], '项目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }

            $list = EnginDutyModel::where(['enginid'=>$data['data']['id']])->select()->toArray();
            $data['list'] = $list;
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function files_engin(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $files = array_filter($param['files']);
            unset($param['files']);

            Db::startTrans();
            try {
                (new OptService())->relation_file($files,'engin',$param['id']);
                (new OptService())->add_flow_log('编辑项目附件', 'engin', $param['id']);
                (new OptService())->add_log_list('编辑项目附件', 'engin', $param['id'], '项目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }
            $data['files'] = (new OptService())->get_file('engin', $data['data']['id']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }



    public function list_engin_elecfile(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['deleted_user','=', 0];
        $where[] = ['comid','=',$this->userinfo['comid']];

        $whereStatus[] = ['isturn','=',1];
        $whereStatus[] = ['status','=',1];


        if(!isset($param['enginid']) || empty($param['enginid'])){
            return outputJson(2000,lang('code_2000'),['data'=>[]]);
        }


        $engininfo = EnginModel::where(['id'=>$param['enginid']])->find();

        $modArr = [
            'engin' => '项目',
            'contract_shi' => '施工合同',
            'contract_cai' => '采购合同',
            'engin_budget' => '成本预算',
            'engin_budbian' => '预算变更',
            'payment_engin' => '项目付款(销售方)',
            'payment_neifu' => '内包付款',
            'payment_neikou' => '内包扣款',
            'payment_bao' => '项目费用报销',
            'income_engin' => '项目收款',
            'engin_bond_jiao' => '项目保证金',
            'engin_bond_fan' => '项目保证金',
            'engin_bond_shou' => '项目保证金',
            'engin_bond_kai' => '项目保证金',
            'piao_kai' => '项目开票',
            'piao_shou' => '项目收票',
            'piao_tax' => '项目税款预缴',
            'stuff_cai' => '材料采购单',
            'stuff_ru' => '材料入库单',
            'stuff_jie' => '材料结算单',
            'labour_shen' => '劳务进度款申报',
            'labour_jie' => '劳务完工结算',
            'labour_ling' => '劳务零星劳务单',
            'device_jin' => '租赁进场登记',
            'device_jie' => '租赁结算',
            'device_lin' => '临时机械登记',
            'subbao_shen' => '分包进度款申报',
            'subbao_jie' => '分包完工结算',
            'engin_xun' => '巡检报告',
            'engin_zheng' => '整改通知',
            'speed_zong' => '总进度计划',
            'speed_month' => '月进度计划',
            'engin_diary' => '施工日志',
            'engin_speed' => '进度填报',
            'visa' => '签证单',
            'engin_chan' => '产值填报(甲方)',
            'engin_junyan' => '竣工验收单',
            'engin_junjie' => '竣工结算单',
            'engin_stamp' => '资料盖章'
        ];

        $list = [];
        foreach ($modArr as $tabname=>$tabtitle){
            if($tabname == 'engin'){
                $idarr = Db::name($tabname)->where($where)->where($whereStatus)->where(['id'=>$param['enginid']])->column('id');
            }elseif($tabname == 'engin_bond_fan'){
                $shouidarr = EnginBondShouModel::where($where)->where($whereStatus)->where(['id'=>$param['enginid']])->column('id');
                $idarr = Db::name($tabname)->where($where)->where($whereStatus)->where(['shouid'=>$shouidarr])->column('id');
            }else{
                $idarr = Db::name($tabname)->where($where)->where($whereStatus)->where(['enginid'=>$param['enginid']])->column('id');
            }

            $file = FileModel::field('id,table,mid,name,ext,size,encpath,fileplain,created_user,created_at,filenav')
                ->where(['comid'=>$this->userinfo['comid'],'table'=>$tabname])
                ->where('mid','in', $idarr)->select()->toArray();
            foreach ($file as $item){
                $item['title'] = $tabtitle;
                $item['enginname'] = $engininfo['name'];
                $item['created_user_name'] = UserModel::get_realname_by_pk($item['created_user']);
                $item['filenav_name'] = (new OptService())->get_base_showname('engin_filenav', $item['filenav']);
                $list[] = $item;
            }
        }

        $subSort = array_column($list,'created_at');
        array_multisort($subSort,SORT_DESC,$list);

        $newData = [];
        $start = ($param['page']-1)*$param['pagesize'];
        for ($i=$start; $i<$start+$param['pagesize']; $i++){
            if(isset($list[$i])){
                $newData[] = $list[$i];
            }
        }

        $data['data']['current_page'] = $param['page'];
        $data['data']['data'] = $newData;
        $data['data']['last_page'] = ceil(count($list)/$param['pagesize']);
        $data['data']['per_page'] = $param['pagesize'];
        $data['data']['total'] = count($list);


        $data['butauth'] = (new MenuService())->get_butauth('engin_elecfile');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function gui_engin_elecfile(Request $request){
        if($request->isPost()){
            $param = $request->post();

            Db::startTrans();
            try {
                FileModel::where('id','in',$param['ids'])->update(['filenav'=>$param['filenav']]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['filenav'] = (new OptService())->get_base_info('engin_filenav');
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function del_engin_elecfile(Request $request){
        $param = $request->post();
        $ids = array_filter(explode(',',$param['id']));
        if(count($ids) == 0){
            return outputJson(4000,'请选择需要删除的数据');
        }
        Db::startTrans();
        try {
            FileModel::where('id','in',$param['id'])->delete();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function rename_engin_elecfile(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入文件名称');
            }

            Db::startTrans();
            try {
                FileModel::where('id','in',$param['id'])->update(['name'=>$param['name']]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id', 0, 'int');
            $data['data'] = FileModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function down_engin_elecfile(Request $request){
        if($request->isPost()){
            $enginid = $request->post('enginid', 0, 'string');
            $engininfo = EnginModel::get_info_by_pk($enginid);
            $ids = $request->post('ids', 0, 'string');
            $fileArr = FileModel::where('id','in',$ids)->select()->toArray();
            if(!$engininfo || !$fileArr){
                return outputJson(4000, '下载失败,无附件信息');
            }

            $file_dir = 'elecfile/'.$this->userinfo['id'].'/';
            if(file_exists($file_dir)){
                $existAtt = scandir($file_dir);
                foreach ($existAtt as $value){
                    if($value != '.' && $value != '..'){
                        unlink($file_dir.$value);
                    }
                }
            }else{
                mkdir($file_dir, 0777);
            }


            $filename = $engininfo['name'].'-电子文件-'.date('YmdHis').'.zip';
            $zip = new \ZipArchive();
            $res = $zip->open($file_dir.$filename, $zip::CREATE);
            if ($res === TRUE) {
                foreach ($fileArr as $_file) {
                    $zip->addFile($_file['oripath'], $_file['name']);
                }
            }
            $zip->close();

            if(file_exists($file_dir.$filename)){
                return outputJson(2000,lang('code_2000'), $file_dir.$filename);
            }else{
                return outputJson(4000, '下载失败');
            }
        }
    }




    public function list_engin_shui_dai(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['shui.deleted_user','=', 0];
        $where[] = ['shui.comid','=',$this->userinfo['comid']];
        $where[] = ['shui.isturn','=',1];
        $where[] = ['shui.status','in',[0,1]];

        if(isset($param['enginid']) && !empty($param['enginid'])){
            $where[] = ['shui.enginid','=', $param['enginid']];
        }

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name|e.number|e.gofuer|shui.flowuser|shui.name|shui.chener','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['shui.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['chener']) && !empty($param['chener'])){
            $where[] = ['shui.chener','like', '%'.$param['chener'].'%'];
        }

        if(isset($param['state']) && $param['state'] != ''){
            $where[] = ['shui.state','=', $param['state']];
        }

        if(isset($param['engin_name']) && !empty($param['engin_name'])){
            $where[] = ['e.name','like', '%'.$param['engin_name'].'%'];
        }
        if(isset($param['engin_number']) && !empty($param['engin_number'])){
            $where[] = ['e.number','like', '%'.$param['engin_number'].'%'];
        }
        if(isset($param['engin_state']) && !empty($param['engin_state'])){
            $where[] = ['e.state','=', $param['engin_state']];
        }
        if(isset($param['engin_gofuer']) && !empty($param['engin_gofuer'])){
            $where[] = ['e.gofuer','like', '%'.$param['engin_gofuer'].'%'];
        }
        if(isset($param['flowuser']) && !empty($param['flowuser'])){
            $where[] = ['shui.flowuser','like', '%'.$param['flowuser'].'%'];
        }
        if(isset($param['created_at']) && !empty($param['created_at'])){
            $created_atArr = explode(' - ', $param['created_at']);
            $where[] = ['shui.created_at','between', [$created_atArr[0].' 00:00:00', $created_atArr[1].' 23:59:59']];
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['shui.status','=', $param['status']];
        }
        if(isset($param['nidt']) && !empty($param['nidt'])){
            $where[] = ['shui.nidt','between', explode(' - ', $param['nidt'])];
        }


        $data['state'] = (new EnginService())->get_engin_shui_state();
        $data['is_state'] = isset($param['state']) ? $param['state'] : '';


        $data['engin_state'] = (new EnginService())->get_engin_state();
        $data['is_engin_state'] = isset($param['engin_state']) ? $param['engin_state'] : '';



        $list = [];
        $info = EnginShuiModel::alias('shui')
            ->field('shui.*,e.name as enginname')
            ->join('engin e','e.id=shui.enginid')
            ->where($where)
            ->where((new MenuService())->get_miss_where('engin_shui', 'shui'))
            ->order('shui.id DESC')
            ->select()->toArray();

        foreach ($info as $item){
            $item['state_name'] = (new ContractService())->get_contract_shi_state_name_tag($item['id'], $item['state']);
            //计算税款承诺书利息
            $item['li_kou_state'] = '未收取';
            $item['li_kaidt'] = '';
            $item['li_jiqi'] = '';
            $item['li_laidt'] = '';
            $item['li_jizhi'] = '';
            $item['li_zhou'] = '';
            $item['li_fee'] = '';
            //1、是否在开票里面关联【并且开票日期不为空,】多个的话，取开票日期最小的数据  关联了才计算利息
            //2、计息期起 = 开票日期的下个月1号   如果到账日期小于计息期起  则不计算利息
            //3、计息期止 = 当前日期  如果有回款或者预收款   则计息期止 = 回款的到账日期
            //4、计息周数 = （计息期止-计息期起+1）/ 7，取整
            //5、利息 = 税款保证金金额 * 周数 * 周息 / 100
            $iskaipiao = PiaokaiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                ->where(['enginid'=>$item['enginid'],'shuiid'=>$item['id'],'shuishou'=>2])
                ->where("dt != '' and dt is not null and dt != '0000-00-00'")
                ->order('dt ASC')->find();
            if($iskaipiao && $iskaipiao['dt'] != '0000-00-00' && $iskaipiao['dt']){
                $item['li_kaidt'] = $iskaipiao['dt'];
                $item['li_jiqi'] = getNextmonthFirstday($iskaipiao['dt']);
                $item['li_jizhi'] = date('Y-m-d');

                $yikouHui = HouKouShuifeiModel::alias('list')
                    ->join('hou_gonghui hou','hou.id=list.zhuid')
                    ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                    ->where(['list.type'=>1,'list.shuiid'=>$item['id']])
                    ->find();
                if($yikouHui){
                    $item['li_laidt'] = $yikouHui['dt'];
                    $item['li_jizhi'] = $yikouHui['dt'];
                    $item['li_kou_state'] = '已收取';
                }else{
                    $yikouYu = HouKouShuifeiModel::alias('list')
                        ->join('hou_gongyu hou','hou.id=list.zhuid')
                        ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                        ->where(['list.type'=>2,'list.shuiid'=>$item['id']])
                        ->find();
                    if($yikouYu){
                        $item['li_laidt'] = $yikouYu['dt'];
                        $item['li_jizhi'] = $yikouYu['dt'];
                        $item['li_kou_state'] = '已收取';
                    }
                }

                if($item['li_jiqi'] < $item['li_jizhi']){
                    $item['li_zhou'] = ceil(  (( strtotime($item['li_jizhi']) - strtotime($item['li_jiqi']) )/24/60/60 + 1) / 7 );
                    $item['li_fee'] = round($item['baofee']*$item['li_zhou']*$item['ratexi']/100, 2);
                }
            }

            if($item['li_kou_state'] == '未收取'){
                $list[] = $item;
            }
        }


        $data['data'] = $list;
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_shui(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['shui.deleted_user','=', 0];
        $where[] = ['shui.comid','=',$this->userinfo['comid']];
        $where[] = ['shui.isturn','=',1];
        $where[] = ['shui.status','in',[0,1]];

        if(isset($param['enginid']) && !empty($param['enginid'])){
            $where[] = ['shui.enginid','=', $param['enginid']];
        }

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name|e.number|e.gofuer|shui.flowuser|shui.name|shui.chener','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['shui.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['chener']) && !empty($param['chener'])){
            $where[] = ['shui.chener','like', '%'.$param['chener'].'%'];
        }

        if(isset($param['state']) && $param['state'] != ''){
            $where[] = ['shui.state','=', $param['state']];
        }

        if(isset($param['engin_name']) && !empty($param['engin_name'])){
            $where[] = ['e.name','like', '%'.$param['engin_name'].'%'];
        }
        if(isset($param['engin_number']) && !empty($param['engin_number'])){
            $where[] = ['e.number','like', '%'.$param['engin_number'].'%'];
        }
        if(isset($param['engin_state']) && !empty($param['engin_state'])){
            $where[] = ['e.state','=', $param['engin_state']];
        }
        if(isset($param['engin_gofuer']) && !empty($param['engin_gofuer'])){
            $where[] = ['e.gofuer','like', '%'.$param['engin_gofuer'].'%'];
        }
        if(isset($param['flowuser']) && !empty($param['flowuser'])){
            $where[] = ['shui.flowuser','like', '%'.$param['flowuser'].'%'];
        }
        if(isset($param['created_at']) && !empty($param['created_at'])){
            $created_atArr = explode(' - ', $param['created_at']);
            $where[] = ['shui.created_at','between', [$created_atArr[0].' 00:00:00', $created_atArr[1].' 23:59:59']];
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['shui.status','=', $param['status']];
        }
        if(isset($param['nidt']) && !empty($param['nidt'])){
            $where[] = ['shui.nidt','between', explode(' - ', $param['nidt'])];
        }


        $data['state'] = (new EnginService())->get_engin_shui_state();
        $data['is_state'] = isset($param['state']) ? $param['state'] : '';


        $data['engin_state'] = (new EnginService())->get_engin_state();
        $data['is_engin_state'] = isset($param['engin_state']) ? $param['engin_state'] : '';

        $data['data'] = EnginShuiModel::alias('shui')
            ->field('shui.*,e.name as enginname')
            ->join('engin e','e.id=shui.enginid')
            ->where($where)
            ->where((new MenuService())->get_miss_where('engin_shui', 'shui'))
            ->order('shui.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['state_name'] = (new ContractService())->get_contract_shi_state_name_tag($item['id'], $item['state']);
                //计算税款承诺书利息
                $item['li_kou_state'] = '未收取';
                $item['li_kaidt'] = '';
                $item['li_jiqi'] = '';
                $item['li_laidt'] = '';
                $item['li_jizhi'] = '';
                $item['li_zhou'] = '';
                $item['li_fee'] = '';
                //1、是否在开票里面关联【并且开票日期不为空,】多个的话，取开票日期最小的数据  关联了才计算利息
                //2、计息期起 = 开票日期的下个月1号   如果到账日期小于计息期起  则不计算利息
                //3、计息期止 = 当前日期  如果有回款或者预收款   则计息期止 = 回款的到账日期
                //4、计息周数 = （计息期止-计息期起+1）/ 7，取整
                //5、利息 = 税款保证金金额 * 周数 * 周息 / 100
                $iskaipiao = PiaokaiModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'status'=>1])
                    ->where(['enginid'=>$item['enginid'],'shuiid'=>$item['id'],'shuishou'=>2])
                    ->where("dt != '' and dt is not null and dt != '0000-00-00'")
                    ->order('dt ASC')->find();
                if($iskaipiao && $iskaipiao['dt'] != '0000-00-00' && $iskaipiao['dt']){
                    $item['li_kaidt'] = $iskaipiao['dt'];
                    $item['li_jiqi'] = getNextmonthFirstday($iskaipiao['dt']);
                    $item['li_jizhi'] = date('Y-m-d');

                    $yikouHui = HouKouShuifeiModel::alias('list')
                        ->join('hou_gonghui hou','hou.id=list.zhuid')
                        ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                        ->where(['list.type'=>1,'list.shuiid'=>$item['id']])
                        ->find();
                    if($yikouHui){
                        $item['li_laidt'] = $yikouHui['dt'];
                        $item['li_jizhi'] = $yikouHui['dt'];
                        $item['li_kou_state'] = '已收取';
                    }else{
                        $yikouYu = HouKouShuifeiModel::alias('list')
                            ->join('hou_gongyu hou','hou.id=list.zhuid')
                            ->where(['hou.comid'=>$this->userinfo['comid'],'hou.deleted_user'=>0,'hou.isturn'=>1,'hou.status'=>1])
                            ->where(['list.type'=>2,'list.shuiid'=>$item['id']])
                            ->find();
                        if($yikouYu){
                            $item['li_laidt'] = $yikouYu['dt'];
                            $item['li_jizhi'] = $yikouYu['dt'];
                            $item['li_kou_state'] = '已收取';
                        }
                    }

                    if($item['li_jiqi'] < $item['li_jizhi']){
                        $item['li_zhou'] = ceil(  (( strtotime($item['li_jizhi']) - strtotime($item['li_jiqi']) )/24/60/60 + 1) / 7 );
                        $item['li_fee'] = round($item['baofee']*$item['li_zhou']*$item['ratexi']/100, 2);
                    }

                }



                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('engin_shui');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function del_engin_shui(Request $request){
        $param = $request->post();
        $data = EnginShuiModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        Db::startTrans();
        try {
            FlowBillModel::where(['id'=>$data['billid']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            EnginShuiModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'engin_shui', $data['id'], '税款承诺书');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function show_engin_shui(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = EnginShuiModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }

        $data['engininfo'] = (new EnginService())->get_engin_showinfo($data['data']['enginid']);

        $data['data']['state_name'] = (new EnginService())->get_engin_shui_state_name($data['data']['state']);

        $qianhui = SuoHuiModel::where(['contractId'=>$data['data']['qysconid']])->select()->toArray();
        $data['qianhui'] = $qianhui;

        $data['files'] = (new OptService())->get_file('engin_shui', $data['data']['id']);
        $data['billinfo'] = (new FlowService())->get_flow_show_info($data['data']['billid']);
        return outputJson(2000,lang('code_2000'), $data);
    }


    public function list_engin_cha(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['cha.deleted_user','=', 0];
        $where[] = ['cha.comid','=',$this->userinfo['comid']];
        $where[] = ['cha.isturn','=',1];
        $where[] = ['cha.status','in',[0,1]];

        if(isset($param['enginid']) && !empty($param['enginid'])){
            $where[] = ['cha.enginid','=', $param['enginid']];
        }

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name|cha.chaer','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['enginname']) && !empty($param['enginname'])){
            $where[] = ['e.name','like', '%'.$param['enginname'].'%'];
        }
        if(isset($param['chatype']) && !empty($param['chatype'])){
            $where[] = ['cha.chatype','=', $param['chatype']];
        }
        if(isset($param['chaer']) && !empty($param['chaer'])){
            $where[] = ['cha.chaer','like', '%'.$param['chaer'].'%'];
        }
        if(isset($param['chadt']) && !empty($param['chadt'])){
            $where[] = ['e.chadt','between', explode(' - ', $param['chadt'])];
        }
        if(isset($param['isxu']) && !empty($param['isxu'])){
            $where[] = ['cha.isxu','=', $param['isxu']];
        }
        if(isset($param['iszheng']) && !empty($param['iszheng'])){
            $where[] = ['cha.iszheng','=', $param['iszheng']];
        }
        if(isset($param['status']) && !empty($param['status'])){
            $where[] = ['cha.status','=', $param['status']];
        }

        $data['chatype'] = (new OptService())->get_base_info('engin_chatype');
        $data['is_chatype'] = isset($param['chatype']) ? $param['chatype'] : '';

        $data['data'] = EnginChaModel::alias('cha')
            ->field('cha.*,e.name as enginname')
            ->join('engin e','e.id=cha.enginid')
            ->where($where)
            ->where((new MenuService())->get_miss_where('engin_cha', 'cha'))
            ->order('cha.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['chatype_name'] = (new OptService())->get_base_showname('engin_chatype', $item['chatype']);

                $item['yaohong'] = false;
                if($item['isxu'] == '是' && $item['iszheng'] == '否'){
                    if(date('Y-m-d') > $item['yaodt']){
                        $item['yaohong'] = true;
                    }
                }
                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('engin_cha');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function edit_engin_cha(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['enginid'])){
                return outputJson(4000, '请选择工程名称');
            }
            if(empty($param['chatype'])){
                return outputJson(4000, '请选择检查类型');
            }
            if(empty($param['chaer'])){
                return outputJson(4000, '请输入检查人');
            }
            if(empty($param['chadt'])){
                return outputJson(4000, '请选择检查日期');
            }
            if(empty($param['chagai'])){
                return outputJson(4000, '请输入检查概况');
            }
            if(empty($param['isxu'])){
                return outputJson(4000, '请选择是否需整改');
            }
            if(empty($param['iszheng'])){
                return outputJson(4000, '请选择是否已整改');
            }

            if($param['isxu'] != '是'){
                $param['gaiqiu'] = '';
                $param['gaier'] = '';
                $param['yaodt'] = '';
                $param['iszheng'] = '';
                $param['zhengdt'] = '';
                $param['gaishuo'] = '';
            }
            if($param['iszheng'] != '是'){
                $param['zhengdt'] = '';
                $param['gaishuo'] = '';
            }


            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);

            Db::startTrans();
            try {
                EnginChaModel::update($param);

                (new OptService())->relation_file($files,'engin_cha',$param['id']);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'engin_cha', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'engin_cha', $param['id'], '工程检查');

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginChaModel::where(['id'=>$id])->find();
            if(!$data['data'] != 0){
                return outputJson(4000, lang('code_4000'));
            }

            $data['engininfo'] = (new EnginService())->get_engin_showinfo($data['data']['enginid']);

            $data['chatype'] = (new OptService())->get_base_info('engin_chatype');

            $data['files'] = (new OptService())->get_file('engin_cha', $data['data']['id']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function del_engin_cha(Request $request){
        $param = $request->post();
        $data = EnginChaModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        Db::startTrans();
        try {
            FlowBillModel::where(['id'=>$data['billid']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            EnginChaModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'engin_cha', $data['id'], '工程检查');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function show_engin_cha(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = EnginChaModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }

        $data['engininfo'] = (new EnginService())->get_engin_showinfo($data['data']['enginid']);
        $data['data']['chatype_name'] = (new OptService())->get_base_showname('engin_chatype', $data['data']['chatype']);


        $data['files'] = (new OptService())->get_file('engin_cha', $data['data']['id']);
        $data['billinfo'] = (new FlowService())->get_flow_show_info($data['data']['billid']);
        return outputJson(2000,lang('code_2000'), $data);
    }




    public function list_engin_kua(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['kua.deleted_user','=', 0];
        $where[] = ['kua.comid','=',$this->userinfo['comid']];
        $where[] = ['kua.isturn','=',1];
        $where[] = ['kua.status','in',[0,1]];
        if(isset($param['enginid']) && !empty($param['enginid'])){
            $where[] = ['kua.enginid','=', $param['enginid']];
        }

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name|e.number|e.gofuer|kua.flowuser','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['engin_name']) && !empty($param['engin_name'])){
            $where[] = ['e.name','like', '%'.$param['engin_name'].'%'];
        }
        if(isset($param['engin_number']) && !empty($param['engin_number'])){
            $where[] = ['e.number','like', '%'.$param['engin_number'].'%'];
        }
        if(isset($param['engin_state']) && !empty($param['engin_state'])){
            $where[] = ['e.state','=', $param['engin_state']];
        }
        if(isset($param['engin_gofuer']) && !empty($param['engin_gofuer'])){
            $where[] = ['e.gofuer','like', '%'.$param['engin_gofuer'].'%'];
        }
        if(isset($param['gui_unit']) && !empty($param['gui_unit'])){
            $where[] = ['gui_unit.id','=', $param['gui_unit']];
        }
        if(isset($param['flowuser']) && !empty($param['flowuser'])){
            $where[] = ['kua.flowuser','like', '%'.$param['flowuser'].'%'];
        }
        if(isset($param['kaidt']) && !empty($param['kaidt'])){
            $where[] = ['kua.kaidt','between', explode(' - ', $param['kaidt'])];
        }
        if(isset($param['created_at']) && !empty($param['created_at'])){
            $created_atArr = explode(' - ', $param['created_at']);
            $where[] = ['kua.created_at','between', [$created_atArr[0].' 00:00:00', $created_atArr[1].' 23:59:59']];
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['kua.status','=', $param['status']];
        }
        if(isset($param['shouer']) && !empty($param['shouer'])){
            $where[] = ['kua.shouer','like', '%'.$param['shouer'].'%'];
        }


        $data['engin_state'] = (new EnginService())->get_engin_state();
        $data['is_engin_state'] = isset($param['engin_state']) ? $param['engin_state'] : '';

        $data['gui_unit'] = (new UserService())->get_chaninfo_all();
        $data['is_gui_unit'] = isset($param['gui_unit']) ? $param['gui_unit'] : '';


        $data['data'] = EnginKuaModel::alias('kua')
            ->field('kua.*,e.name as enginname,gui_unit.name as gui_unit_name')
            ->join('engin e','e.id=kua.enginid')
            ->leftJoin('dept gui_unit','gui_unit.id=e.gui_unit')
            ->where($where)
            ->where((new MenuService())->get_miss_where('engin_kua', 'kua'))
            ->order('kua.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){

                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('engin_kua');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function edit_engin_kua(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['enginid'])){
                return outputJson(4000, '请选择工程名称');
            }
            if(empty($param['shouer'])){
                return outputJson(4000, '请选择发包方(购买方)');
            }
            if(empty($param['ratenum'])){
                return outputJson(4000, '请输入纳税人识别号');
            }
            if(empty($param['money'])){
                return outputJson(4000, '请输入本次开具跨区域涉税金额');
            }


            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);




            Db::startTrans();
            try {
                EnginKuaModel::update($param);

                (new OptService())->relation_file($files,'engin_kua',$param['id']);
                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'engin_kua', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'engin_kua', $param['id'], '跨区域涉税事项');

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginKuaModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }

            $engininfo = (new EnginService())->get_engin_showinfo($data['data']['enginid']);
            $data['engininfo'] = $engininfo;

            $data['files'] = (new OptService())->get_file('engin_kua', $data['data']['id']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function del_engin_kua(Request $request){
        $param = $request->post();
        $data = EnginKuaModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        Db::startTrans();
        try {
            FlowBillModel::where(['id'=>$data['billid']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            EnginKuaModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'engin_kua', $data['id'], '跨区域涉税事项');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function show_engin_kua(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = EnginKuaModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }

        $engininfo = (new EnginService())->get_engin_showinfo($data['data']['enginid']);
        $data['engininfo'] = $engininfo;

        $data['files'] = (new OptService())->get_file('engin_kua', $data['data']['id']);
        $data['billinfo'] = (new FlowService())->get_flow_show_info($data['data']['billid']);
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function files_engin_kua(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $files = array_filter($param['files']);
            unset($param['files']);

            Db::startTrans();
            try {
                (new OptService())->relation_file($files,'engin_kua',$param['id']);
                (new OptService())->add_flow_log('编辑附件', 'engin_kua', $param['id']);
                (new OptService())->add_log_list('编辑附件', 'engin_kua', $param['id'], '跨区域涉税事项');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginKuaModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }
            $data['files'] = (new OptService())->get_file('engin_kua', $data['data']['id']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }






















}
